Sub topic 3
Iterating over a Vec
This chapter assumes you know basic Rust syntax, ownership and borrowing (move, &, &mut), and how to run programs with cargo. You should also have seen Vec::new, vec! and push.
A for loop over a Vec can borrow its elements, borrow them mutably, or consume the whole vector. Which one you get depends on what you pass to the loop.
Three ways to loop
| Expression | Item type | Effect on the `Vec` |
|---|---|---|
| `v.iter()` or `&v` | `&T` | Read-only borrow. `v` stays usable. |
| `v.iter_mut()` or `&mut v` | `&mut T` | Mutable borrow. No other access while the loop runs. |
| `v.into_iter()` or `v` | `T` | Moves `v` into the loop. `v` cannot be used afterward. |
for x in &v is shorthand for for x in v.iter(). The same goes for &mut v and iter_mut.
Reading, changing and consuming
fn main() {
let mut v = vec![1, 2, 3];
for x in v.iter_mut() {
*x *= 2;
}
let total: i32 = v.iter().sum();
println!("{:?} {}", v, total); // [2, 4, 6] 12
for x in v {
println!("{x}");
}
// v has been moved into the loop and can no longer be used here.
}iter_mut gives a &mut i32, so you write through it with *x. The iter call borrows v only for the duration of sum. The last loop uses v by value, so each x is an owned i32, and the vector is gone afterward.
flowchart TDDo not add that block. The diagram below is the one for this chapter.
Common errors
Using a vector after a by-value loop is the most frequent mistake. The compiler reports "borrow of moved value". If you still need v, loop over &v.
Changing the length of a vector while you loop over it is also rejected. The loop holds a borrow, so v.push(...) inside for x in &v fails to compile. This is the same rule covered in the chapter on borrowing. Collect the changes into a second vector, or use retain afterward.
Forgetting the * is a third source of errors. With iter_mut, x *= 2 does not compile because x is a reference. Write *x *= 2.
Position and iterator adapters
When you need the index, use enumerate. It pairs each item with its position.
fn main() {
let names = vec!["Ana", "Bo", "Cy"];
for (i, name) in names.iter().enumerate() {
println!("{i}: {name}");
}
let long: Vec<&&str> = names.iter().filter(|n| n.len() > 2).collect();
println!("{:?}", long); // ["Ana"]
}Prefer enumerate over for i in 0..v.len() with v[i]. It avoids the bounds check on each access and cannot index out of range.
Exercise
You write for x in v { println!("{x}"); } and then call v.len() on the next line. The compiler rejects it. Why, and how do you fix it while keeping the loop?
Show answer
Looping over v by value calls into_iter, which moves the Vec into the loop, so v is no longer valid afterward. Loop over &v (or v.iter()) instead. Each x is then a &T, and v remains usable after the loop.