Sub topic 3
Rust Iterator Consumers and Practical Pipelines
Assume you know ownership, borrowing, Option, Result, generics, and basic iterator adapters such as map and filter.
Consumers: sum, fold, count, find, any, all
Iterator adapters build a pipeline, but consumers run it and produce a result.
| Consumer | Result |
|---|---|
| `sum` | Adds all items |
| `fold` | Builds one value from an accumulator |
| `count` | Counts items |
| `find` | Returns the first matching item |
| `any` and `all` | Test predicates |
fn main() {
let values = [2, 4, 6, 9];
let total: i32 = values.iter().sum();
let product = values.iter().fold(1, |acc, n| acc * n);
let even_count = values.iter().filter(|n| **n % 2 == 0).count();
let first_large = values.iter().find(|n| **n > 5);
let has_odd = values.iter().any(|n| **n % 2 != 0);
let all_positive = values.iter().all(|n| **n > 0);
println!("{total} {product} {even_count} {first_large:?}");
println!("{has_odd} {all_positive}");
}fold receives an initial value and combines each item with it. Consumers such as find, any, and all can stop early.
Gathering results with `collect`
collect consumes an iterator and gathers its items into a collection. Rust often needs a type annotation because many types implement FromIterator.
fn main() {
let doubled: Vec<i32> = (1..=4).map(|n| n * 2).collect();
println!("{doubled:?}");
}Collecting Result values into Result<Vec<_>, _> stops at the first error.
Putting closures and iterators together
Closures express each transformation locally. This pipeline keeps only long words, records their positions, and converts them to uppercase.
fn main() {
let words = ["red", "violet", "green", "blue"];
let result: Vec<(usize, String)> = words
.iter()
.enumerate()
.filter(|(_, word)| word.len() > 3)
.map(|(index, word)| (index, word.to_uppercase()))
.collect();
println!("{result:?}");
}Writing your own iterator
Implement Iterator by defining next. Returning None means the sequence is finished.
struct Countdown(u32);
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
None
} else {
let value = self.0;
self.0 -= 1;
Some(value)
}
}
}Performance and pitfalls
Iterator chains are usually zero-cost abstractions: the compiler can inline closures and remove intermediate storage, producing code comparable to a loop. They remain lazy until a consumer runs them.
Exercise
What does (1..=5).filter(|n| n % 2 == 1).sum() return?
Show answer
It returns 9, because it consumes the odd values 1, 3, and 5.