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
Given the following code (playground):
The current output is:
When you use
.get_mutinstead, you get a helpful hint advising you to extract the immutable borrow to a local variable (playground):Ideally the output for the first code snippet should contain the same help message.
@rustbot label +D-terse +D-confusing +D-newcomer-roadblock