Skip to content

Rust should explain why a closure call requires a mutable borrow #80313

Description

@Aaron1011

The following code:

fn main() {
    let mut my_var = false;
    let callback = || {
        my_var = true;
    };
    callback();
}

produces the following error:

error[E0596]: cannot borrow `callback` as mutable, as it is not declared as mutable
 --> src/main.rs:6:5
  |
3 |     let callback = || {
  |         -------- help: consider changing this to be mutable: `mut callback`
...
6 |     callback();
  |     ^^^^^^^^ cannot borrow as mutable

error: aborting due to previous error

The expression callback() tries to mutably borrow callback due to the mutation of my_var. However, the error message doesn't explain this.

We should add a note to the error message pointing to the span of the upvar that caused us to need the mutable borrow.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.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