我不明白为什么这行不通:
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[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
我使用test
的可变方法hi
。可变方法hi
可能会更改test
的某些字段。这意味着可以写入a
中的b
或test
。因此,我通过了a
,并且b
的可变引用没有违反任何内容。因为a
和b
位于test
内部。