1

This Rust code does not compile:

struct Foo {
    x: i32,
}

impl Foo {
    fn bar(&mut self, x: i32) {}

    fn foo(&mut self) {
        self.bar(self.x);
    }
}

It fails because of this lifetime error:

error[E0503]: cannot use `self.x` because it was mutably borrowed
 --> src/main.rs:9:18
  |
9 |         self.bar(self.x);
  |         ----     ^^^^^^ use of borrowed `*self`
  |         |
  |         borrow of `*self` occurs here

I don't understand why the Rust compiler has an issue with the above code. x gets passed by value, so there is no borrow occurring to any of self's member variables when bar gets called. The self that bar gets is the same self that foo has, since a copy of the member variables is sent to bar during the function call.

I don't see any logical reason why the code violates Rust's borrow mechanics.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Benjamin Konz
  • 45
  • 3
  • 8
  • Related: [Cannot borrow as immutable because it is also borrowed as mutable in function arguments](https://stackoverflow.com/q/41187296/155423) – Shepmaster Feb 24 '18 at 21:00

0 Answers0