← Fundamentals
Fundamentals

Rust iterators and adapters

Why does map do nothing until something consumes it?

Follow item demand, ownership and stopping conditions through a Rust iterator chain.

Outcome

Predict when adapter closures run and in which order, choose iter, iter_mut or into_iter, collect into a Vec or a Result, consume a pipeline once, and change a collection with retain or extend instead of during a loop over it.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Iterator adapter
A step such as the shown map or filter that wraps an iterator and applies its callback when items are requested.
Consumer
An operation that requests items. Some request the whole stream and some stop early; a method taking self by value moves a non-Copy iterator value unless the receiver is a borrow.
into_iter
For Vec<T> by value, IntoIterator consumes the vector and yields owned T values. Reference receivers can instead yield borrowed items.
retain
Keeps only the elements for which a test returns true, changing the Vec in place.
Short-circuiting
Stopping a pipeline early, as collect into Result does at the first Err.

Adapters describe how to request items

A Rust iterator produces items through next. Adapters such as map and filter build another iterator that transforms or selects items when requested. A consumer such as collect, sum or a loop requests items; some consumers stop before the source is exhausted.

The item type also carries the access contract. iter borrows elements, iter_mut borrows them mutably, and into_iter uses the collection’s IntoIterator implementation. For a Vec, owned iteration consumes the vector, while borrowed iteration leaves ownership with the caller. Choose both the item access and the consumer to fit the task.

01Laziness

The Map callback waits for an item request

A candle shop imports delivery lots, clears sold-out scents and reconciles an order file. The tools must retain each delivery, keep the remaining shelf in order, and report every rejected physical row. Trace when a pipeline requests data and which collection remains available to its caller.

A reduced delivery preview doubles three lot quantities so each transformation is visible in the trace. Predict where built appears, then follow the final sum that requests those items.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let lots = [1, 2, 3];

    let doubled = lots.iter().map(|lot| {
        println!("map {lot}");
        lot * 2
    });

    println!("built");
    let total: i32 = doubled.sum();

    println!("total {total}");
}
What is printed first?
Rust · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
rustc --edition=2024 main.rs -o main && ./main

Use the Rust command shown with the examples. The printed trace lines instrument callback execution; distinguish constructing an adapter from requesting an item through it.

02Item by item

This map/filter chain runs item by item

Another preview converts ten-candle pack counts into quantities and keeps the larger lots. Both mapping and selection log their work. Predict whether the trace is grouped by stage or by requested item.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let lots = [1, 2, 3];

    let kept: Vec<i32> = lots
        .iter()
        .map(|lot| {
            println!("map {lot}");
            lot * 10
        })
        .filter(|lot| {
            println!("filter {lot}");
            *lot > 10
        })
        .collect();

    println!("{kept:?}");
}
In which order do the lines appear?

03Which loop owns what

The receiver type decides what the loop takes

The shelf tool still needs its scent list after displaying it. Trace what the shown Vec<String> loop takes, then predict whether the later count is available.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let scents = vec!["fig".to_owned(), "pine".to_owned()];

    for scent in scents {
        println!("{scent}");
    }

    println!("{} scents", scents.len());
}
What does rustc do?

04Stopping early

collect into a Result stops at the first error

The importer first checks whether an entire tiny batch can be decoded. Its counter records which fields are inspected. Predict how the collected Result affects the later field after x.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let fields = ["1", "x", "3"];
    let mut parsed = 0;

    let all: Result<Vec<u32>, _> = fields
        .iter()
        .map(|field| {
            parsed += 1;
            field.parse::<u32>()
        })
        .collect();

    println!("{} {}", all.is_err(), parsed);
}
What is printed?
Loading An Err ends this collect before the next field…

05Repair the candle shop

Restock, clear sold-out scents, then report

The shop needs three working tools: append delivery lots, remove sold-out scents while preserving shelf order, and reconcile an order file’s accepted quantities and rejected physical row numbers.

This lab is Rust-only. Each file contains its imports, reader and complete caller.

Repair the candle shop

Retain deliveries, clear adjacent sold-out records, then reconcile all order rows without duplicating rejection evidence.

  1. easy · F-ITER-V4-1 Restock the shelf
  2. medium · F-ITER-V4-2 Clear sold-out scents
  3. hard · F-ITER-V4-3 Report the orders
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.