Skip to content

Confusing error message when attempting to &mut a mutable reference #36542

Closed
@Ixrec

Description

@Ixrec

Playground: https://play.rust-lang.org/?gist=0bde8d89f0ef683de58561b7cae3a096&version=nightly&backtrace=0
Code:

fn foo(b: &mut u64) {
    let x = &mut b;
}

fn main() {
    let mut x = 42;
    foo(&mut x);
}

Current Error:

error: cannot borrow immutable argument `b` as mutable
 --> <anon>:2:18
  |
1 | fn foo(b: &mut u64) {
  |        - use `mut b` here to make mutable
2 |     let x = &mut b;
  |                  ^ cannot borrow mutably

error: aborting due to previous error

This error is confusing because:

  • It refers to an argument of type &mut T as "immutable".
  • It explicitly suggests "adding more muts", when the correct solution is to remove the redundant "&mut".

Some of the immediate reactions in #rust include:

[21:48:05] <Ixrec> the message ought to be more like "cannot mutably borrow self because it's already a mutable reference"
[21:49:29] <misdreavus> "hint: self is already &mut Foo, do you mean to make a &mut &mut Foo?"
[21:52:00] <sebk> "self is already &mut" would have explained it for me

I think misdreavus' suggestion might be the best and/or simplest option.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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