Closed
Description
Given the following code (playground):
fn main() {
let mut vec = vec![0u32; 420];
vec[vec.len() - 1] = 123;
}
The current output is:
error[E0502]: cannot borrow `vec` as immutable because it is also borrowed as mutable
--> src/main.rs:4:9
|
4 | vec[vec.len() - 1] = 123;
| ----^^^^^^^^^-----
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
| mutable borrow later used here
When you use .get_mut
instead, you get a helpful hint advising you to extract the immutable borrow to a local variable (playground):
fn main() {
let mut vec = vec![0u32; 420];
*vec.get_mut(vec.len() - 1).unwrap() = 123;
}
error[E0502]: cannot borrow `vec` as immutable because it is also borrowed as mutable
--> src/main.rs:4:18
|
4 | *vec.get_mut(vec.len() - 1).unwrap() = 123;
| ------------^^^^^^^^^-----
| | | |
| | | immutable borrow occurs here
| | mutable borrow later used by call
| mutable borrow occurs here
|
help: try adding a local storing this argument...
--> src/main.rs:4:18
|
4 | *vec.get_mut(vec.len() - 1).unwrap() = 123;
| ^^^^^^^^^
help: ...and then using that local as the argument to this call
--> src/main.rs:4:6
|
4 | *vec.get_mut(vec.len() - 1).unwrap() = 123;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
Ideally the output for the first code snippet should contain the same help message.
@rustbot label +D-terse +D-confusing +D-newcomer-roadblock
Metadata
Metadata
Assignees
Labels
Area: Messages for errors, warnings, and lintsDiagnostics: Confusing error or lint that should be reworked.Diagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: An error or lint that doesn't give enough information about the problem at hand.Relevant to the compiler team, which will review and decide on the PR/issue.