The following minimal example does not compile:
fn main() {
let mut v = Vec::new();
foo(&mut v);
}
fn foo(v_ref: &mut Vec<u8>) {
for v in v_ref{
println!("{}", v);
}
for v in v_ref{
println!("{}", v);
}
}
The compiler suggests to modify the first for loop to this, which does compile.
for v in &mut *v_ref{
The reasoning given by the compiler is:
move occurs because
v_ref
has type&mut Vec<u8>
, which does not implement theCopy
trait
v_ref
moved due to this implicit call to.into_iter()
Question 1: Why is this necessary? It's already a reference, shouldn't the for loop give the reference back after we're done with it?
Question 2: Why does the fix work? As I understand it, the new mutable reference should invalidate the old one.