I'm having some trouble understanding what's going on in this simple example:
let mut my_vec = vec![1, 2, 3, 4];
for v in &mut my_vec {
*v += 1;
}
I would not expect this code to compile, as I'd assume that in the for loop, v
would need to have been marked as &mut
for it to work. But actually, marking it as &mut v
makes the compilation fail. Why?!
My line of thought is as follows:
- I want to increment
v
by 1, sov
needs to be both a reference and mutable, hence the variable declaration in the for loop should be&mut v
; my_vec
on the for-loop needs then to be marked asmut
, as its values are going to be mutated, and as a reference, as we want to change the values ofmy_vec
;my_vec
then also needs to be marked asmut
, otherwise no mutations can be performed on it.
In other words, if I had not run the code through a compiler, this is what I would have come up with:
let mut my_vec = vec![1, 2, 3, 4];
for &mut v in &mut my_vec {
*v += 1;
}
Where am I failing?