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.