Skip to content

Bogus "consider specifying this binding's type" when reference differs in mutability #113767

Open
@lukas-code

Description

@lukas-code

Code

fn get() -> &'static Vec<i32> {
    todo!()
}

fn main() {
    let x = get();
    x.push(1);
}

Current output

error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference
 --> src/main.rs:7:5
  |
7 |     x.push(1);
  |     ^^^^^^^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
  |
help: consider specifying this binding's type
  |
6 |     let x: &mut Vec<i32> = get();
  |          +++++++++++++++

Desired output

error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference
 --> src/main.rs:7:5
  |
7 |     x.push(1);
  |     ^^^^^^^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
  |

Rationale and extra context

The type is defined as immutable reference by the return type of the function and specifying it as a mutable reference in the let binding won't help.

Other cases

This seems to happen only if

  • the immutable reference doesn't come from a local borrow (eg. let x = &vec![];)
  • the variable x goes through auto(de)ref with a method call or field access (eg. x.field = 1)

Anything else?

@rustbot label A-suggestion-diagnostics D-incorrect

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.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