Skip to content

Provide help on closures capturing self causing borrow checker errors #105761

Closed
@estebank

Description

@estebank

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

A-borrow-checkerArea: The borrow checkerA-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions