Compose the data flow.
Distinguish borrowed iteration, consuming iteration, and collection.
01 Understand the contract
An Iterator produces a sequence of optional next items. Adapters such as map and filter are lazy: they describe work that runs when a consumer requests elements. Consumers include sum, count, fold, collect, and a for loop. iter borrows elements, iter_mut borrows them mutably, and into_iter usually consumes the collection. Iterator chains can be concise, but a normal loop is often clearer when the work has multiple state changes or complex early exits.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let values = vec![1, 2, 3, 4];
let total: i32 = values.iter().filter(|&&n| n % 2 == 0).map(|&n| n * n).sum();
println!("total={total}, retained={}", values.len());
}total=20, retained=4
- 1
iter preserves the vector.
- 2
filter receives a reference to the iterator item, producing the double-reference pattern here.
- 3
sum drives the lazy chain.
cargo run -p lesson_iterators03 Mind the boundary
04 Your next build
Use enumerate and filter_map to collect indexes of negative readings.
Reveal one possible solution +
fn main() {
let values = [2, -1, 4, -3];
let indexes: Vec<_> = values
.iter()
.enumerate()
.filter_map(|(i, &n)| if n < 0 { Some(i) } else { None })
.collect();
assert_eq!(indexes, [1, 3]);
}05 Check your reasoning
Which operation drives a lazy iterator to produce a result?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.