I dont understand why this doesn't work:
struct Test {
pub a: Vec<u8>,
pub b: Vec<u8>,
}
impl Test {
pub fn hi(&mut self) {
self.write(&mut self.a, &mut self.b);
}
fn write(&mut self, _a: &mut Vec<u8>, _b: &mut Vec<u8>) {}
}
fn main() {
let mut test = Test {
a: Vec::new(),
b: Vec::new(),
};
test.hi();
}
Error:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:8:9
|
8 | self.write(&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
--> src/main.rs:8:20
|
8 | self.write(&mut self.a, &mut self.b);
| ---- ----- ^^^^^^^^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
error[E0499]: cannot borrow `self.b` as mutable more than once at a time
--> src/main.rs:8:33
|
8 | self.write(&mut self.a, &mut self.b);
| ---- ----- ^^^^^^^^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
I use a mutable method of test
, which is hi
. The mutable method hi
may change some field of test
. It means that a
or b
of test
may be written. So I pass a
and b
's mutable reference doesn't violate anything. Because a
and b
live inside test
.