Sub topic 6
Iterating with for and ranges
This chapter covers how for loops work in Rust, how ranges are built, and the common mistakes people make when iterating. It assumes you can build and run a program with cargo, know the primitive types, and understand let and let mut. You should also have read the chapters on loop and while.
What a for loop does
A for loop takes any value that can be turned into an iterator and runs its body once per item. An iterator is a value that produces a sequence of items, one at a time, until it runs out.
fn main() {
for n in 1..4 {
println!("{n}");
}
}This prints 1, 2 and 3. Unlike C-style loops, there is no counter you manage by hand. You cannot forget to increment it, and you cannot step past the end of a collection by accident.
The loop variable (n above) is a new binding for each pass. It is immutable by default. Write for mut n in ... if you want to change your copy inside the body. This does not affect the source of the items.
Ranges
A range is a value that describes a span of integers (or other ordered types such as char). Rust has several forms.
| Syntax | Type | Meaning |
|---|---|---|
| `a..b` | `Range` | From `a` up to, but not including, `b` |
| `a..=b` | `RangeInclusive` | From `a` up to and including `b` |
| `a..` | `RangeFrom` | From `a` with no upper end |
| `..b` | `RangeTo` | No lower end, up to but not including `b` |
| `..` | `RangeFull` | Everything |
Only the first three can drive a for loop. The ones without a start have no first item to begin from, so they are used for slicing, such as &v[..3].
fn main() {
for i in 0..3 {
print!("{i} ");
}
println!();
for i in 0..=3 {
print!("{i} ");
}
println!();
for c in 'a'..='e' {
print!("{c} ");
}
println!();
}The output is 0 1 2, then 0 1 2 3, then a b c d e.
An empty range simply runs zero times. If the start is greater than or equal to the end, nothing happens and there is no error:
fn main() {
let mut runs = 0;
for _ in 5..2 {
runs += 1;
}
println!("{runs}");
}This prints 0. A common mistake is expecting 5..2 to count down. It does not. Use .rev() for that.
Counting down and stepping
Ranges are iterators, so you can chain adapter methods onto them. An adapter is a method that takes an iterator and returns a new, modified iterator.
fn main() {
for i in (1..=3).rev() {
println!("{i}");
}
for i in (0..20).step_by(5) {
print!("{i} ");
}
println!();
}The parentheses around the range matter. Without them, 1..=3.rev() would apply .rev() to the 3, which does not compile. The second loop prints 0 5 10 15.
step_by takes the step size as a usize, and it panics if the step is 0. The first item is always the start of the range. Each later item adds the step, and the range's end still decides when to stop.
Iterating over collections
Anything that implements the IntoIterator trait can go in a for loop. The trait converts a value into an iterator. The for loop calls it for you. Three forms matter in practice, and each treats ownership differently.
fn main() {
let mut names = vec![String::from("Ada"), String::from("Grace")];
for name in &names {
println!("read {name}");
}
for name in &mut names {
name.push('!');
}
for name in names {
println!("owned {name}");
}
}| Loop head | Item type | Effect on the collection |
|---|---|---|
| `for x in &v` | `&T` | Borrows it. You can use `v` afterwards. |
| `for x in &mut v` | `&mut T` | Borrows it mutably. You can edit items in place. |
| `for x in v` | `T` | Moves it. `v` is gone after the loop. |
The last form is the surprising one. After for name in names, the vector has been consumed, and using names again is a compile error ("borrow of moved value"). If you only want to read, borrow with &.
Arrays work the same way. Since Rust 2021, for x in [1, 2, 3] yields the values themselves, not references. Slices such as &v[1..] yield references.
Getting the index with enumerate
Often you want both the position and the item. Do not write for i in 0..v.len() and then index with v[i]. That works, but it adds a bounds check on each access and makes off-by-one errors easy. Use enumerate, which pairs each item with its index.
fn main() {
let fruits = ["apple", "pear", "plum"];
for (i, fruit) in fruits.iter().enumerate() {
println!("{i}: {fruit}");
}
}The loop head (i, fruit) is a pattern. It destructures each (usize, &&str) tuple into two names. .iter() is the explicit form of looping over a borrow. It is equivalent to &fruits here.
Other adapters that are useful in loops:
zipwalks two iterators in step and stops at the shorter one.skip(n)andtake(n)drop or limit items.chars()iterates over the characters of a&str.bytes()iterates over its bytes.chunks(n)andwindows(n)on slices give groups of items.
fn main() {
let a = [1, 2, 3];
let b = ["one", "two", "three", "four"];
for (n, word) in a.iter().zip(b.iter()) {
println!("{n} = {word}");
}
}Only three lines are printed, because a ends first.
How for is desugared
Knowing what the compiler does with a for loop explains several behaviors. Roughly, this loop:
fn main() {
for x in 0..3 {
println!("{x}");
}
}is the same as this one:
fn main() {
let mut iter = IntoIterator::into_iter(0..3);
while let Some(x) = iter.next() {
println!("{x}");
}
}Each call to next returns Some(item) or, when the sequence ends, None. The for loop stops at the first None. Two consequences follow. First, for accepts anything with IntoIterator, including your own types. Second, because iter is a mutable local value, the loop owns the iterator for its duration.
Control flow inside for
break exits the loop, and continue skips to the next item. Both work as in other languages.
fn main() {
for n in 1..=10 {
if n % 2 == 0 {
continue;
}
if n > 7 {
break;
}
print!("{n} ");
}
println!();
}This prints 1 3 5 7. Unlike loop, a for loop cannot break with a value. Its type is always (), because the loop might finish without ever hitting a break. If you need to search for a result, either use loop, or use an iterator method such as find:
fn main() {
let found = (1..100).find(|n| n * n > 50);
println!("{found:?}");
}This prints Some(8). Labels, covered in the next chapter, let break and continue target an outer loop.
Edge cases and common errors
Integer overflow in ranges. 0..=255u8 works correctly. The inclusive range tracks whether it has finished, so it does not wrap around. 0..256u8 does not compile, because 256 does not fit in u8. If you need every u8 value, use ..=.
Modifying a collection while iterating. This fails to compile:
fn main() {
let mut v = vec![1, 2, 3];
for x in &v {
if *x == 2 {
v.push(4);
}
}
}The loop holds an immutable borrow of v for its whole duration, so push conflicts with it. The borrow checker is preventing a real bug, since push can reallocate and invalidate the iterator. Collect the changes first and apply them after the loop, or build a new vector with filter and collect.
Float ranges. 0.0..1.0 is a valid Range<f64>, but it is not an iterator, because floats have no "next value". for x in 0.0..1.0 does not compile. Loop over integers and convert, such as for i in 0..10 { let x = i as f64 / 10.0; }.
Unused loop variable. If you do not need the item, name it _, as in for _ in 0..3. This avoids a compiler warning and signals your intent.
Reversed inclusive ranges. (1..=n).rev() is safe for n = 0: the range is empty, so nothing runs. The unsigned version of this bug, for i in (0..=n - 1).rev(), panics in debug builds when n is 0, because n - 1 underflows. Write (0..n).rev() instead.
Performance. for over a range or a slice iterator compiles to code as fast as a hand-written index loop. Rust removes the bounds checks where it can prove the index is in range, and iterator code is usually at least as fast. Prefer the iterator form for clarity first.
Choosing between loop forms
- Use
forwhen you have a collection or a known range. It is the default choice. - Use
whilewhen the condition depends on state that changes in unpredictable ways. - Use
loopwhen you need to run until some event and may want to break with a value.
Exercise
What does this program print, and why does the second line not compile if you add println!("{}", v.len()); after the loop?
fn main() {
let v = vec![10, 20, 30];
for (i, x) in v.into_iter().enumerate().skip(1) {
println!("{i}:{x}");
}
}
Show answer
It prints 1:20 and 2:30. enumerate assigns indexes 0, 1, 2 first, and skip(1) then drops the first pair, so the indexes keep their original values. v.into_iter() consumes the vector, so v has been moved. Using v.len() afterwards gives a "borrow of moved value" error. Use v.iter() or for ... in &v to keep v usable.
Exercise
Write a for loop that prints the even numbers from 10 down to 2, one per line.
Show answer
for n in (2..=10).rev().stepby(2) { println!("{n}"); } prints 10, 8, 6, 4, 2. The range is reversed first, so `stepby(2) starts at 10 and takes every second item. Writing (2..=10).step_by(2).rev()` also works here, because the range has an exact size and both orders land on the even numbers.