Skip to content

&mut &T coerced to &T suggests &mut mut x #57431

Description

@cramertj

This code (play):

struct X;
impl X {
    fn mutate(&mut self) {}
}

fn main() {
    let term = Some(X);
    let term = match &term {
        Some(term) => &mut term,
        None => term.as_ref().unwrap(),
    };
    term.mutate();
}

Produces these errors:

error[E0596]: cannot borrow `term` as mutable, as it is not declared as mutable
 --> src/main.rs:9:23
  |
9 |         Some(term) => &mut term,
  |                       ^^^^^^^^^
  |                       |
  |                       cannot borrow as mutable
  |                       try removing `&mut` here

error[E0596]: cannot borrow `*term` as mutable, as it is behind a `&` reference
  --> src/main.rs:12:5
   |
9  |         Some(term) => &mut term,
   |                       --------- help: consider changing this to be a mutable reference: `&mut mut term`
...
12 |     term.mutate();
   |     ^^^^ `term` is a `&` reference, so the data it refers to cannot be borrowed as mutable

error: aborting due to 2 previous errors

Note that the second error suggests changing &mut term to &mut mut term, which obviously won't fix the issue.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)A-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-confusingDiagnostics: Confusing error or lint that should be reworked.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