I'm trying to make a struct that holds an mutable reference. Accessing the mutable reference multiple times through its field works fine. However, if I use a getter instead, it does not compile.
struct IntBorrower<'inner>(&'inner mut i32);
impl<'outer: 'inner, 'inner> IntBorrower<'inner> {
fn int_mut(&'outer mut self) -> &'inner mut i32 {
&mut self.0
}
//this compiles
fn do_something(&'outer mut self) {
{
*self.0 += 5;
}
{
*self.0 += 5;
}
}
//this does not compile
fn do_something_but_with_getters(&'outer mut self) {
{
*self.int_mut() += 5;
}
{
*self.int_mut() += 5;
}
}
}
fn main() {}
I get this error:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:26:14
|
22 | *self.int_mut() += 5;
| ---- first mutable borrow occurs here
...
26 | *self.int_mut() += 5;
| ^^^^ second mutable borrow occurs here
27 | }
28 | }
| - first borrow ends here
Shouldn't the first mutable borrow end inside those brackets just like in the previous function? Why does this happen?