Sub topic 3
Iterating over a Vec
This chapter covers the three ways to loop over a Vec<T>: by shared reference, by mutable reference, and by value. It also covers how a for loop is built on iterators, how to get indices alongside elements, and the mistakes that cause compiler errors. It assumes you know basic Rust syntax, the rules of ownership and borrowing (move, &, &mut), Option with match, and how to run programs with cargo.
The three ways to loop
A Vec<T> can be iterated in three modes. Each mode decides what the loop variable is, and whether the Vec is still usable afterwards.
| Loop header | Loop variable type | Vec afterwards |
|---|---|---|
| `for x in &v` or `v.iter()` | `&T` | Still usable, unchanged |
| `for x in &mut v` or `v.iter_mut()` | `&mut T` | Still usable, possibly changed |
| `for x in v` or `v.into_iter()` | `T` | Moved, no longer usable |
The following program uses all three.
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.
}The first loop borrows v mutably. Each x is a &mut i32, so you must dereference it with *x to change the number it points to. The call to iter().sum() borrows v again, this time shared, and the borrow ends when sum returns. The last loop consumes v. After it, any use of v is a compile error ("borrow of moved value").
How a for loop works
A for loop is shorthand for calling into_iter() on the expression after in, then calling next() until it returns None. The method next() returns Option<Item>. This is why the three loop headers behave differently: IntoIterator is implemented three times for vectors.
Vec<T>implementsIntoIteratorwithItem = T.&Vec<T>implements it withItem = &T.&mut Vec<T>implements it withItem = &mut T.
Writing for x in &v is therefore the same as for x in v.iter(). Both forms are common. Prefer &v when the loop is the whole point, and .iter() when you plan to chain adapters such as map or filter.
You can drive an iterator by hand to see this mechanism.
fn main() {
let v = vec!["a", "b"];
let mut it = v.iter();
println!("{:?}", it.next()); // Some("a")
println!("{:?}", it.next()); // Some("b")
println!("{:?}", it.next()); // None
}Note that it must be declared mut, because next() changes the iterator's internal position.
Shared references: reading
Use iter() when you only need to look at the elements. The items are &T, so many Rust operations work on them without any explicit dereference, because method calls and comparisons with {} formatting see through references.
fn main() {
let names = vec![String::from("Ana"), String::from("Bo")];
for name in &names {
println!("{} has {} letters", name, name.len());
}
// names is still available because the loop only borrowed it.
println!("{}", names.len()); // 2
}Because the loop only borrows, you can create any number of shared iterators over the same Vec at the same time. What you cannot do is change the Vec while one is alive. That rule is covered in the chapter on the borrow checker.
Mutable references: changing in place
Use iter_mut() when you want to modify each element without building a new Vec. The loop variable is &mut T. For a primitive such as i32 you write *x += 1. For a type with fields or methods, auto-dereferencing means you can often skip the star.
struct Item {
name: String,
qty: u32,
}
fn main() {
let mut stock = vec![
Item { name: String::from("bolt"), qty: 4 },
Item { name: String::from("nut"), qty: 0 },
];
for item in stock.iter_mut() {
item.qty += 10; // no explicit * needed for field access
}
for item in &stock {
println!("{}: {}", item.name, item.qty);
}
}While an iter_mut() loop runs, the Vec is exclusively borrowed. You cannot read stock.len() or index into stock inside the loop body. The compiler rejects it because the mutable borrow is still active.
By value: consuming
Looping over v itself, or calling into_iter(), moves each element out of the Vec and gives you ownership. Use it when you want to transform the elements into something else, or pass them to a function that takes ownership.
fn shout(s: String) -> String {
s.to_uppercase()
}
fn main() {
let words = vec![String::from("hi"), String::from("there")];
let loud: Vec<String> = words.into_iter().map(shout).collect();
println!("{:?}", loud); // ["HI", "THERE"]
// words is moved; using it here would not compile.
}This avoids cloning. Without into_iter(), you would have to call .clone() on every string to get owned values from a borrowed Vec.
Indices and positions
When you need the position of each element, use enumerate(). It wraps each item in a tuple (index, item), with the index starting at 0.
fn main() {
let v = vec!["x", "y", "z"];
for (i, item) in v.iter().enumerate() {
println!("{i}: {item}");
}
}Avoid the C-style pattern for i in 0..v.len() { v[i] ... }. It works, but each v[i] performs a bounds check and can panic, and it hides intent. Iterators read the elements directly and cannot go out of bounds.
Some tasks do need indices, such as comparing neighbours. Slice methods cover most of these cases without manual indexing.
fn main() {
let v = vec![1, 4, 9, 16];
for pair in v.windows(2) {
println!("diff {}", pair[1] - pair[0]);
}
// diff 3
// diff 5
// diff 7
}windows(n) yields overlapping slices of length n. Its sibling chunks(n) yields non-overlapping groups, with a shorter final group if the length is not a multiple of n.
Adapters worth knowing
Iterators are lazy. Calls such as map and filter build a new iterator but do no work until something consumes it, such as a for loop, sum, or collect.
fn main() {
let v = vec![1, 2, 3, 4, 5, 6];
let even_squares: Vec<i32> = v
.iter()
.filter(|&&x| x % 2 == 0)
.map(|&x| x * x)
.collect();
println!("{:?}", even_squares); // [4, 16, 36]
println!("{}", v.iter().any(|&x| x > 5)); // true
println!("{:?}", v.iter().position(|&x| x == 4)); // Some(3)
}The patterns |&&x| and |&x| look odd at first. Here iter() yields &i32. The filter closure receives a reference to that item, so its argument is &&i32. The map closure receives the &i32 directly. Each & in the pattern removes one layer of reference. Because i32 is Copy, this is cheap. For types that are not Copy, keep the reference and use methods instead.
Common errors
- Pushing inside a loop over the same Vec.
for x in &v { v.push(*x); }fails because&vholds a shared borrow for the whole loop. Collect the new items into a separateVecand extend afterwards. - Removing while iterating. The same borrow rule applies to
remove. Useretainto drop elements that match a condition. - Using
vafterfor x in v. Iterate over&v, or clone theVecfirst if you truly need both. - Forgetting
*withiter_muton primitives.x += 1wherex: &mut i32is a type error. Write*x += 1. - Type mismatch from references. Summing
iter()gives you&i32items.sum::<i32>()handles that, but comparing&i32toi32with==does not compile. Dereference with*xor pattern match with|&x|.
Exercise
Given let mut v = vec![3, 8, 5];, write code that doubles every element in place, then prints each element with its index. Which two iteration modes did you use, and is v still usable afterwards?
Show answer
Use for x in v.iter_mut() { *x *= 2; } (mutable reference), then for (i, x) in v.iter().enumerate() { println!("{i}: {x}"); } (shared reference). Neither loop moves v, so it is still usable. The output is 0: 6, 1: 16, 2: 10.
Exercise
This code does not compile: let names = vec![String::from("a")]; for n in names { println!("{n}"); } println!("{}", names.len());. Why, and what is the smallest fix?
Show answer
for n in names calls into_iter() on the Vec, which moves it into the loop, so names.len() uses a moved value. Change the loop to for n in &names, which only borrows the Vec.