Open
Description
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