Sub topic 6
Iterating with for and ranges
This chapter assumes you can build and run a program with cargo, know Rust's primitive types, and understand let and let mut. It also assumes you have seen loop and while. Here you will use for to walk over ranges and collections, and you will learn the mistakes that trip people up most often.
The working model
A for loop does not count. It asks a value for an iterator, then calls next on that iterator until it returns None. Each Some(item) is bound to your loop variable, and the body runs once per item.
Because of this, for works on anything that can become an iterator: ranges, vectors, slices, arrays, and the results of methods like .chars() or .iter().
fn main() {
let mut total = 0;
for i in 1..=4 {
total += i;
}
println!("{total}");
}The loop variable i is a fresh binding on each pass. You do not declare it with let, and it is immutable unless you write for mut i in ....
Ranges
Rust has two range forms you will use constantly.
| Syntax | Meaning | Values for `1..4` / `1..=4` |
|---|---|---|
| `a..b` | Start included, end excluded | 1, 2, 3 |
| `a..=b` | Both ends included | 1, 2, 3, 4 |
Ranges are values. Methods such as .rev() and .step_by() change how they are walked.
fn main() {
for i in (1..=3).rev() {
println!("{i}");
}
for i in (0..10).step_by(5) {
println!("{i}");
}
}Wrap the range in parentheses before calling .rev(). Without them, the method would bind to the end value only, and the code would not compile.
Iterating over collections
How you write the loop decides whether the collection is consumed, borrowed, or modified.
fn main() {
let mut names = vec![String::from("Ana"), String::from("Bo")];
for name in &names {
println!("{name}");
}
for name in &mut names {
name.push('!');
}
for name in names {
println!("{name}");
}
}for x in &vborrows each item immutably.vis still usable afterward.for x in &mut vborrows each item mutably, so you can change items in place.for x in vmovesvinto the loop and gives you owned items.vcannot be used afterward.
When you need the position as well as the item, use .enumerate(). It yields (index, item) pairs, which you can unpack right in the loop header.
fn main() {
let scores = [90, 72, 85];
for (i, score) in scores.iter().enumerate() {
println!("{i}: {score}");
}
}Flow of a for loop
break and continue work as in loop and while. break leaves the loop. continue skips to the next call to next.
Common errors
- Using a vector after
for x in v. The loop movedv. Loop over&vif you need it again. - Indexing with a loop counter. Code such as
for i in 0..v.len() { v[i] }compiles, but it performs a bounds check on each access and is easy to get wrong. Preferfor x in &v, or.enumerate()when you need the index. - Off-by-one with
...0..v.len()is correct for indexes.0..=v.len()would panic on the last index. - Mutating while iterating. Calling
v.push(...)insidefor x in &vis rejected by the borrow checker, because the loop holds a borrow ofv. - Empty ranges.
5..1is valid but produces no items. It does not count down. Use(1..5).rev()to go downward.
fn main() {
for i in 5..1 {
println!("never printed: {i}");
}
println!("done");
}Exercise
What does this program print, and why can words not be used after the loop?
let words = vec!["a", "b", "c"];
for (i, w) in words.into_iter().enumerate().skip(1) {
println!("{i}{w}");
}
Show answer
It prints "1b" and then "2c". enumerate numbers items from 0, and skip(1) drops the first pair. into_iter() consumes the vector, so words is moved and cannot be used afterward.
Exercise
Write a loop header that visits the numbers 10, 8, 6, 4, 2 in that order.
Show answer
for i in (2..=10).rev().step_by(2). Reversing first yields 10, 9, 8, ..., and step_by(2) takes every second value starting from 10.