Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ REUSE THE IDEA
BUILD NOTE 29 / 53

Compose the data flow.

Distinguish borrowed iteration, consuming iteration, and collection.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/iterators/src/main.rs
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());
}
↳ EXPECTED OUTPUT
total=20, retained=4
  1. 1

    iter preserves the vector.

  2. 2

    filter receives a reference to the iterator item, producing the double-reference pattern here.

  3. 3

    sum drives the lazy chain.

From the extracted rust-workbench folder
cargo run -p lesson_iterators

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use enumerate and filter_map to collect indexes of negative readings.

Reveal one possible solution +
solutions/iterators/src/main.rs
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

QUICK SIGNAL CHECK

Which operation drives a lazy iterator to produce a result?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.