以可变方法更改一些可变字段

时间:2019-08-05 11:18:13

标签: rust

我不明白为什么这行不通:

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中的btest。因此,我通过了a,并且b的可变引用没有违反任何内容。因为ab位于test内部。

0 个答案:

没有答案