What does the error mean in this case:
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3, 4, 5];
v[v[1]] = 999;
}
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/main.rs:3:7
|
3 | v[v[1]] = 999;
| --^----
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
| mutable borrow later used here
I found that indexing is implemented via the Index
and IndexMut
traits and that v[1]
is syntactic sugar for *v.index(1)
. Equipped with this knowledge, I tried to run the following code:
use std::ops::{Index, IndexMut};
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3, 4, 5];
*v.index_mut(*v.index(1)) = 999;
}
To my surprise, this works flawlessly! Why doesn't the first snippet work, but the second one does? The way I understand the documentation, they should be equivalent, but this obviously isn't the case.
See Question&Answers more detail:os