Sub topic 10
Iterators Are Lazy
This chapter assumes you know ownership and borrowing, basic generics and trait bounds, and Option. You should also have met the Iterator trait and the common adapters such as map and filter. Here you will learn what "lazy" means for iterators, how to see it happen, and which errors it causes in practice.
What lazy means
An iterator adapter does no work when you call it. Calling map, filter, take or zip returns a new struct that wraps the previous iterator and stores your closure. No element is read and no closure runs.
Work happens only when something calls next. A consumer such as sum, collect, count or a for loop calls next repeatedly, and each call pulls one item through the whole chain.
Here is the example that shows it:
fn main() {
let v = vec![1, 2, 3];
let it = v.iter().map(|x| {
println!("visiting {}", x);
x * 2
});
println!("before");
let total: i32 = it.sum();
println!("total = {}", total);
}The output is:
before
visiting 1
visiting 2
visiting 3
total = 2The last line is wrong as written, so check it yourself: the doubled values are 2, 4 and 6, so the program prints total = 12. The correct output is:
before
visiting 1
visiting 2
visiting 3
total = 12The println!("before") line comes first even though map appears earlier in the source. The map call only built the adapter. The closure ran when sum drove the iterator.
The compiler warns you
Because adapters do nothing alone, forgetting a consumer is a real bug. Rust marks adapters with #[must_use], so this code compiles with a warning:
fn main() {
let v = vec![1, 2, 3];
v.iter().map(|x| println!("{}", x));
}The warning reads "unused Map that must be used" and adds "iterators are lazy and do nothing unless consumed". Nothing is printed. To run side effects, use a for loop or for_each:
fn main() {
let v = vec![1, 2, 3];
v.iter().for_each(|x| println!("{}", x));
for x in &v {
println!("{}", x);
}
}Prefer a for loop when the body has side effects. Use map when you want to transform values.
Items flow one at a time
A lazy chain does not process the whole collection in stages. It does not first run filter over every element and then run map over the survivors. Instead, each item travels through every stage before the next item starts.
This example makes the order visible:
fn main() {
let total: i32 = (1..=4)
.filter(|n| {
println!("filter {}", n);
n % 2 == 0
})
.map(|n| {
println!("map {}", n);
n * 10
})
.sum();
println!("total = {}", total);
}The output interleaves the two closures:
filter 1
filter 2
map 2
filter 3
filter 4
map 4
total = 60Item 1 is dropped by filter, so map never sees it. Item 2 passes both stages before item 3 is even read. This is called a pull model, because the consumer pulls each item through the chain.
Note that one call to next on filter can call the source several times. filter keeps asking until an item passes or the source ends.
Short-circuiting
Laziness lets a chain stop early. If a consumer needs only some items, the rest are never produced. This matters when the source is expensive or infinite.
fn main() {
let first_big_square = (1..)
.map(|n| n * n)
.find(|sq| *sq > 50);
println!("{:?}", first_big_square); // Some(64)
let firsts: Vec<u32> = (1..)
.filter(|n| n % 7 == 0)
.take(3)
.collect();
println!("{:?}", firsts); // [7, 14, 21]
}(1..) is an unbounded range. It is safe here because find and take(3) stop pulling once they have what they need. Without them, the loop would run until the integer overflows. In a debug build that panics, and in a release build it wraps around silently.
These consumers short-circuit:
| Consumer | Stops when |
|---|---|
| `find` | the predicate first returns true |
| `any` | the predicate first returns true |
| `all` | the predicate first returns false |
| `position` | the predicate first returns true |
| `take(n)` (adapter) | n items have been yielded |
| `take_while` (adapter) | the predicate first returns false |
Consumers such as sum, count and fold must read every item. Calling sum on an infinite iterator never returns.
Side effects and order
Closures in a lazy chain run at a time and in an order you may not expect. Three consequences follow.
- Side effects are delayed. A closure that logs, mutates state or reads a counter runs only when the consumer arrives.
- Side effects can be skipped. If a later
takeorfindstops early, closures for the remaining items never run. - Side effects interleave. With several adapters, their closures alternate item by item, as the filter and map example showed.
This is why map with side effects is discouraged. The code is hard to read, and it silently stops working if someone removes the consumer.
fn main() {
let mut calls = 0;
let found = [5, 8, 12, 20]
.iter()
.inspect(|_| calls += 1)
.any(|&n| n > 10);
println!("{} after {} calls", found, calls); // true after 3 calls
}inspect is the adapter meant for peeking at items while debugging. Here any stops at 12, so the fourth element is never visited and calls is 3. The closure borrows calls mutably, and that borrow ends once the chain is consumed, so reading calls afterward is allowed.
Laziness and borrowing
A lazy adapter holds whatever its closure captured, and it holds it until the chain is consumed or dropped. This keeps borrows alive longer than you may expect.
fn main() {
let mut v = vec![1, 2, 3];
let doubled = v.iter().map(|x| x * 2); // borrows v immutably
// v.push(4); // error[E0502]: cannot borrow `v` as mutable
let result: Vec<i32> = doubled.collect();
v.push(4);
println!("{:?} {:?}", result, v);
}doubled borrows v through iter() for as long as doubled is used. If you uncomment v.push(4) before collect, the compiler rejects the program, because collect still needs the borrow afterward. After collect, the borrow is over, so push works.
The same idea applies to closures that capture variables. A lazy map closure that reads factor sees the value at the time the closure runs, not when you wrote the chain. In safe Rust the borrow checker prevents you from changing factor in between, so the value cannot change. With Cell or RefCell it can, and then the delay becomes visible.
use std::cell::Cell;
fn main() {
let factor = Cell::new(2);
let scaled = [1, 2, 3].iter().map(|x| x * factor.get());
factor.set(10); // allowed: Cell uses shared access
let out: Vec<i32> = scaled.collect();
println!("{:?}", out); // [10, 20, 30]
}Many people expect [2, 4, 6]. The closure reads factor only when collect runs, after set(10).
Making a chain eager
Sometimes you want work done now. Call a consumer such as collect to materialize the results into a Vec, then use that.
fn main() {
let names = vec!["ada", "grace", "linus"];
let upper: Vec<String> = names.iter().map(|s| s.to_uppercase()).collect();
println!("{:?}", upper);
}Collecting early costs an allocation, but it fixes the values, releases the borrow on the source, and lets you iterate the result more than once. Do it when you need any of those, not by default.
A lazy chain can also be returned or stored without running it. A function that returns impl Iterator<Item = u32> gives the caller a recipe, and the caller decides when to consume it.
fn evens_squared(limit: u32) -> impl Iterator<Item = u32> {
(0..limit).filter(|n| n % 2 == 0).map(|n| n * n)
}
fn main() {
for sq in evens_squared(7) {
println!("{}", sq); // 0, 4, 16, 36
}
}Nothing is computed when evens_squared returns. The for loop does the work.
Summary of rules
- Adapters build a new iterator and run no closures.
- A consumer drives the chain by calling
next. - Each item passes through every stage before the next item starts.
- Short-circuiting consumers stop early, so later closures may never run.
- Captured borrows stay alive until the chain is consumed or dropped.
Exercise
What does this program print, and why? let v = vec![1, 2, 3, 4]; let r: Vec<i32> = v.iter().inspect(|x| println!("saw {}", x)).filter(|x| **x % 2 == 0).take(1).collect(); println!("{:?}", r);
Show answer
It prints "saw 1", "saw 2", then "[2]". The chain is lazy, so each item goes through inspect and filter one at a time. Item 1 is printed by inspect and rejected by filter. Item 2 is printed and accepted. take(1) is then satisfied and stops pulling, so items 3 and 4 are never visited by inspect.
Exercise
A colleague writes numbers.iter().map(|n| total += n); to sum a list, and nothing happens. Explain why, and show two fixes.
Show answer
map only builds an adapter and never calls its closure until a consumer pulls items. The compiler warns that the Map is unused. Fix 1: use a loop, for n in &numbers { total += n; }. Fix 2: use a consumer, either numbers.iter().for_each(|n| total += n); or, better, let total: i32 = numbers.iter().sum();.