Given a closure that immutably captures self, you can easily cause a lifetime error
struct S;
impl S {
fn foo(&mut self) {
let x = || {
self.bar();
};
self.qux();
x();
}
fn bar(&self) {}
fn qux(&mut self) {}
}
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/main.rs:7:9
|
4 | let x = || {
| -- immutable borrow occurs here
5 | self.bar();
| ---- first borrow occurs due to use of `*self` in closure
6 | };
7 | self.qux();
| ^^^^^^^^^^ mutable borrow occurs here
8 | x();
| - immutable borrow later used here
The usual solution here is to explicitly pass self into the closure as an this: &Self argument to side-step the issue. We should suggest doing so.
Given a closure that immutably captures
self, you can easily cause a lifetime errorThe usual solution here is to explicitly pass
selfinto the closure as anthis: &Selfargument to side-step the issue. We should suggest doing so.