Skip to content

Taking a mutable reference to self in a closure leads to suggestion to change "self" in function signature #111554

Closed
@simon-frankau

Description

@simon-frankau

Code

struct Test {
}

impl Test {
    pub fn test(&mut self) {
        // Removing || changes the suggestion to 
        || test2(&mut self);
    }
}

fn test2(_: &mut Test) {
}

Current output

error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
   --> src/sound_player.rs:870:11
    |
869 |     pub fn test(&mut self) {
    |                      ---- help: consider changing this to be mutable: `mut self`
870 |     || test2(&mut self);
    |              ^^^^^^^^^ cannot borrow as mutable

Desired output

error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
   --> src/sound_player.rs:870:8
    |
870 |     test2(&mut self);
    |           ^^^^^^^^^ cannot borrow as mutable
    |
note: the binding is already a mutable borrow
   --> src/sound_player.rs:869:17
    |
869 |     pub fn test(&mut self) {
    |                 ^^^^^^^^^
help: try removing `&mut` here
    |
870 -     test2(&mut self);
870 +     test2(self);

Rationale and extra context

The output is already good without a closure. Somehow, putting the call in a closure changes the error message to one that's less helpful.

Other cases

Removing the "||" fixes the suggestion.

Anything else?

I can't think of anything. I'm happy to answer any questions you have.

I'm building through cargo, so I'm not 100% sure of the rustc version, but I get:

$ rustc --version
rustc 1.66.0 (69f9c33d7 2022-12-12)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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