While a slightly modified, explicit version does not compile:
let v = vec![1, 2, 3];
let iter = v.iter();
loop {
let i = if let Some(i) = iter.next() { i } else { break };
println!("{}", i);
}
error[E0596]: cannot borrow `iter` as mutable, as it is not declared as mutable
--> src/main.rs:5:34
|
3 | let iter = v.iter();
| ---- help: consider changing this to be mutable: `mut iter`
4 | loop {
5 | let i = if let Some(i) = iter.next() { i } else { break };
| ^^^^ cannot borrow as mutable
Not quite. The IntoIterator (and thus the for loop) takes complete ownership of Self— You don’t have to mark the iterator/collection as mutable because it never appears modified within your code and becomes completely inaccessible after the loop body.
Another trick is that the thing you're iterating can be a reference, and then that is consumed by the loop instead of the container behind it. So for x in &v will call IntoIterator::into_iter(&v), which &Vec implements the same as v.iter(). This also works for &mut v and v.iter_mut().