I have the following code (simplified):
trait Trait1 {
fn f(&mut self);
}
struct S1;
impl Trait1 for S1 {
fn f(&mut self) { }
}
trait Trait2<'a, T: 'a + Trait1> {
fn field(&'a mut self) -> &'a mut T;
fn do_something(&'a mut self) {
self.field().f();
self.field().f();
}
}
struct S2(S1);
impl<'a> Trait2<'a, S1> for S2 {
fn field(&'a mut self) -> &'a mut S1 {
&mut self.0
}
}
The lifetimes are required because of another code, don't bother about them.
The important thing here is that the compiler complains:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/lib.rs:15:9
|
10 | trait Trait2<'a, T: 'a + Trait1> {
| -- lifetime `'a` defined here
...
14 | self.field().f();
| ------------
| |
| first mutable borrow occurs here
| argument requires that `*self` is borrowed for `'a`
15 | self.field().f();
| ^^^^ second mutable borrow occurs here
But I don't understand: the compiler can see that even though Trait2.field()
borrows self
as mutable, it was finished executing. As I understand, the borrowing of self
only affects the return value. Here it is not even used in the return value. Shouldn't the compiler accept that?