« use of moved value » when using a reference to a vector

A mutable reference is unique, so it can indeed not be copied, and the for loop will consume it. However, it is possible to reborrow a mutable reference, which creates a sub-mutable reference to the same thing. While the reborrow exists, the original is not usable to enforce the uniqueness.

To reborrow, use &mut *the_mut_ref.

for n in &mut *v {
    ...
}

Note that reborrows happens automatically whenever you use a mutable reference in a place that can only accept a mutable reference, but for loops can accept many types, including non-mutable references, so it doesn't happen here.

6 Likes