Skip to content

Confusing error when trying to re-borrow a function argument #75871

Closed
@JaniM

Description

@JaniM

It is a common mistake, especially for beginners, to attempt to reborrow function arguments when calling other functions.

I tried this code:

struct T;
fn foo(x: &mut T) {}
fn bar(x: &mut T) {
    foo(&mut x)
}

I expected to see this happen: Compile error following what the above code does if foo(&x) is attempted instead.

error[Exxxx]: mismatched types
 --> src/lib.rs:6:9
  |
6 |     foo(&mut x)
  |         ^^ expected `&mut T`, found `&mut &mut T`
  |
  = note; you don't need to use `&mut` when you already have a mutable reference

Instead, this happened: Misleading error.

error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable
 --> src/lib.rs:6:9
  |
5 | fn bar(x: &mut T) {
  |        - help: consider changing this to be mutable: `mut x`
6 |     foo(&mut x)
  |         ^^^^^^ cannot borrow as mutable

Meta

1.45.2 srable & 1.47.0 nightly on the playground

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=768e5a2d690393f89aed38be3fa5dee6

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