Sub topic 10
Iterators are lazy
This chapter assumes you know ownership and borrowing, closures, and the Iterator trait with next. It also assumes you have seen adapters such as map and filter.
Adapters do no work by themselves
An adapter like map or filter does not walk the data. It returns a new iterator that wraps the old one and remembers your closure. Nothing runs until something calls next. That something is usually a consumer such as sum, collect, or a for loop.
The compiler warns about this with unused_must_use: iterator adapters are marked #[must_use] because an unconsumed chain does nothing.
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 = 6"before" prints first because building it only constructed a Map value. The closure ran during sum, which called next until the iterator returned None.
Items flow one at a time
A chain does not process the whole collection in stages. Each call to next on the outer iterator pulls one item through every adapter in turn. Consider this chain, which has two closures that print:
fn main() {
let v = vec![1, 2, 3, 4];
let first_big = v
.iter()
.inspect(|x| println!("saw {}", x))
.map(|x| x * 10)
.find(|x| *x > 15);
println!("{:?}", first_big);
}The output is:
saw 1
saw 2
Some(20)find stops as soon as it has an answer, so 3 and 4 are never touched. A step-by-step pipeline that built a full intermediate Vec after each stage would have visited everything.
What laziness gives you
- Early exit.
find,any,all, andtakestop pulling items once they have a result. - No intermediate collections. Each item moves through the chain without allocating a
Vecbetween stages. - Infinite sources. A range like
1..has no end, but(1..).filter(|n| n % 7 == 0).take(3)finishes after three matches.
fn main() {
let multiples: Vec<u32> = (1..).filter(|n| n % 7 == 0).take(3).collect();
println!("{:?}", multiples); // [7, 14, 21]
}Side effects and ordering
Because evaluation is driven by the consumer, side effects inside closures happen in a consumer-defined order and may not happen at all. Keep closures in adapters free of important side effects. Use for_each or a for loop when you want the effect to be the point.
fn main() {
let v = vec![1, 2, 3];
// Warning: unused `Map` that must be used. Nothing is printed.
v.iter().map(|x| println!("{}", x));
// This prints, because for_each consumes the iterator.
v.iter().for_each(|x| println!("{}", x));
}Exercise
What does this program print, and why? let v = vec![1, 2, 3, 4, 5]; let r: Vec<i32> = v.iter().map(|x| { println!("m{}", x); x * 2 }).filter(|x| x % 4 == 0).take(1).collect(); println!("{:?}", r);
Show answer
It prints m1, m2, and then [4]. The chain is lazy, so collect pulls items one at a time. Item 1 becomes 2 and fails the filter. Item 2 becomes 4 and passes. take(1) is then satisfied, so no more items are pulled and m3 to m5 never print.