0
votes

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?

1
Not only can you get mutable references to two distinct elements at the same time. You can get mutable references to all elements at the same time: 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. - kmdreko

1 Answers

0
votes

In the end you do not hold a mut reference more than once,in x = value the reference is moved into x. It would be different if that line was first in the loop:

fn main() {
    let mut lst = vec![1, 2, 3];
    let mut x = &mut 0;

    for value in &mut lst {
        x = value;

        *value += 1;
        *x += 1;
    }

    *x += 1;
    println!("{:?}", &lst);
}

In where of course the compiler complains:

error[E0503]: cannot use `*value` because it was mutably borrowed
 --> src/main.rs:8:9
  |
6 |         x = value;
  |             ----- borrow of `*value` occurs here
7 | 
8 |         *value += 1;
  |         ^^^^^^^^^^^ use of borrowed `*value`
9 |         *x += 1;
  |         ------- borrow later used here