I guess this is a trivial one but I have no idea how to make it work. So I wanna save space and thus not make any extra copies of anything if I do not need to. I wanna switch the content of two vectors in my object through a private method. The example below i am showing is an oversimplification of a more complicated example where shift is not as simple as here but a more complicated arithmetic shuffle (here I am just rewriting vectors):
Example:
struct Obj {
a: Vec<u8>,
b: Vec<u8>,
}
impl Obj {
pub fn new(aa: Vec<u8>, bb: Vec<u8>) -> Self {
Obj { a: aa, b: bb }
}
fn swtch(&mut self, v_a: &mut Vec<u8>, v_b: &mut Vec<u8>) {
let mut x = 0;
let tmp = v_b.clone();
for i in v_a.into_iter() {
v_b[x] = *i;
x = x + 1;
}
x = 0;
for i in tmp.into_iter() {
v_a[x] = i;
x = x + 1;
}
}
pub fn xcng(&mut self, key: &str) -> &mut Self {
match key {
"ab" => self.swtch(&mut self.a, &mut self.b),
"ba" => self.swtch(&mut self.b, &mut self.a),
_ => {}
};
self
}
}
fn main() {
let a = b"abcdefgh".to_vec();
let b = b"ijklmn".to_vec();
let obj = Obj::new(a, b);
obj.xcng("ba").xcng("ab").xcng("bb");
println!("{:?} {:?}", obj.a, obj.b);
}
my primary goal is to be able to apply xcng()
function as many times I want on obj
-> obj.xcng("ba").xcng("ab").xcng("ba")....;
However as you can see
Compiling playground v0.0.1 (/playground)
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:28:21
|
28 | "ab" => self.swtch(&mut self.a, &mut self.b),
| ^^^^^-----^-----------^^^^^^^^^^^^^^
| | | |
| | | first mutable borrow occurs here
| | first borrow later used by call
| second mutable borrow occurs here
error[E0499]: cannot borrow `self.a` as mutable more than once at a time
I am doing something I am not supposed to
can anyone help in solving this conundrum ?
thnx