Closed
Description
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.
Metadata
Metadata
Assignees
Labels
Area: The borrow checkerArea: Closures (`|…| { … }`)Area: Messages for errors, warnings, and lintsArea: Suggestions generated by the compiler applied by `cargo fix`Diagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: An error or lint that needs small tweaks.Relevant to the compiler team, which will review and decide on the PR/issue.