I'm trying to learn Rust's ownership and lifetimes in more detail, and I'm very confused by this piece of code:
let mut lst = vec![1, 2, 3];
let mut x = &mut 0;
for value in &mut lst {
*value += 1;
*x += 1;
x = value;
}
*x += 1;
println!("{:?}", &lst);
From what I understand, Rust disallows having more than one mutable reference to any value, and a mutable reference to an element in a vector also borrows the vector itself. So it should not be possible to simultaneously have mutable references to two elements in a vector.
But in the code above, the body of the loop stores a mutable reference to an element in lst
in x
outside the loop. Then, in the next iteration, it takes another mutable reference to a different element in lst
, giving me two mutable references to two elements in the list at once.
So my question is: Why is this allowed?
lst.iter_mut().collect::<Vec<_>>()
. This works because each mutable reference from the iterator will be distinct. Much like you can simultaneously have mutable references to different fields in a struct. – Imparity