0

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 himay 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.

hellow
  • 12,430
  • 7
  • 56
  • 79
JACK M
  • 2,627
  • 3
  • 25
  • 43
  • 1
    "doesn't violate anything" → If you where allowed to do this, what would prevent you from using `&mut self.a` in `write` and then get *another* mutable reference to `self.a`, violating Rust's aliasing rules? – mcarton Aug 05 '19 at 11:21
  • as mcarton says, you already have a mutable reference to `self` which could give you `self.a` as well. It's not possible. I think the error message is pretty clear here, isn't it? – hellow Aug 05 '19 at 11:22
  • Please always show the *complete* error message, not just a snippet – hellow Aug 05 '19 at 11:23

0 Answers0