If I want to consume an iterator by hand, it has to be mutable:
let test = vec![1, 2, 3];
let mut test_mut = test.iter();
while let Some(val) = test_mut.next() {
println!("{:?}", val);
}
But I can happily consume it with a for
loop, even if it's immutable.
let test = vec![1, 2, 3];
let test_imm = test.iter();
for val in test_imm {
println!("{:?}", val);
}
I think this works because test_imm
is moved into the for loop's block, so test_imm
can't be used by the outer block any more and is (from the point of view of the outer block) immutable up until the for loop, and then it's inaccessible, so it's okay.
Is that right? Is there more to be explained?
See Question&Answers more detail:os