Rust · Chapter 13 of 26

Closures and iterators

By the end of this chapter you can write closures and say what they capture, walk any collection with an iterator, build a chain of adapters that filters, changes and combines values, finish it with a consumer that sums, counts, finds or collects, explain why an iterator does nothing until something consumes it, and write an iterator of your own. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Traits and data
  • 4 tasks
  • Rust
  • In the all labs plan

The first 2 chapters of Rust are free. This one comes with the all labs plan.

Why you need this

Every ten days Neha's payout run asks dozens of questions of the day's 10,164 pourings: what each farmer earned, each society's accepted milk, each shift's totals, the richest can, whether any can at a society was rejected. Each answer is a pass over the pourings that keeps some, looks at one field and adds, counts or groups.

With the Rust you know so far, every question is a loop like this one, which counts the buffalo cans with fat of 8.0% or more:

let mut rich = 0;
for i in 0..day.len() {
    if day[i].kind == doodh::Kind::Buffalo && day[i].fat >= 80 {
        rich += 1;
    }
}

It works, but the question ("buffalo, fat 80 or more, how many") is buried in the plumbing: a mut counter, an index, a range that must stop at exactly len(), an if. Write 0..=day.len() by mistake and it panics with "index out of bounds" on the last round. Twenty questions are twenty such loops, each with its own counter to get wrong. Rust's iterators let you write the question itself, day.iter().filter(..) .count(), and closures are the small functions you hand them to say what to keep and what to look at.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    accepted.rs: a society's accepted milk, in one chain

    Write pub fn accepted_ml(day: &[Collection], society: &str) -> u32 in accepted.rs. It returns the millilitres of every accepted pouring at one society: only pourings whose society is the id given and whose status is Status::Accepted, their ml added up. Write it as one iterator chain, with no for, while or loop anywhere in accepted.rs (the Check reads the file for them).

    With day = doodh::collections(), the Check expects accepted_ml(&day, "S001") to be 3430730, "S014" 1070590, "S120" 655190 and "S999" (no such society) 0. On a short list of its own with S050 cans of 4000 ml (accepted), 2500 ml (rejected) and 1250 ml (accepted), and a 7000 ml can at S051, it expects 5250 for "S050".

  2. Task 2

    by_farmer.rs: what each farmer earned

    Write pub fn paise_by_farmer(day: &[Collection]) -> HashMap<String, u64> in by_farmer.rs. It returns a map from each farmer's id to the paise all their pourings earned. Every farmer who poured is in it, even one whose every can was rejected (with 0). Build it from an iterator over the pourings: with fold, or a for loop over day.iter().

    With day = doodh::collections(), the Check expects 4773 farmers in the map, F10001 11468, F10150 162666, F10193 0 (its one can was rejected), and the values to add up to 293257264. An empty slice must give an empty map. On a short list of its own where F20001 poured twice (300 and 45 paise) and F20002's only can was rejected, it expects F20001 345, F20002 0 and 2 farmers.

    Collecting (farmer, paise) pairs straight into a HashMap keeps only each farmer's last pouring, so a farmer who poured twice would get only the second amount.

  3. Task 3

    shifts.rs: an iterator over a society's shifts

    In shifts.rs, write pub fn shifts(day: &[Collection], society: &str) -> Shifts and implement Iterator for Shifts with type Item = ShiftTotal (ShiftTotal has pub fields shift: Shift, pourings: usize, ml: u32 and paise: u64). shifts keeps only that society's pourings, in the order they come in day. Each call of next gathers the next run of pourings that have the same shift, one after another, and returns their ShiftTotal: the shift, how many pourings, their ml added up and their paise added up. After the last run next returns None, and keeps returning None.

    With day = doodh::collections(), the Check expects shifts(&day, "S001") to give ShiftTotal { shift: Morning, pourings: 211, ml: 1972820, paise: 6966003 }, then ShiftTotal { shift: Evening, pourings: 195, ml: 1559530, paise: 5449894 }, then None, and None again. shifts(&day, "S999") must give None at once. On a short list of its own whose S050 pourings go morning (1000 ml, 10 paise), morning (2000, 20), evening (3000, 30), morning (4000, 0), with an S051 can between them, it expects three ShiftTotals: Morning 2 pourings 3000 ml 30 paise, Evening 1 3000 30, Morning 1 4000 0.

  4. Task 4 · interview question

    Interview: payday.rs, the map that never ran

    pub fn pay_all(bills: &mut [Bill]) -> u64 in payday.rs must mark every bill that is not paid yet and has more than 0 paise as paid, and return the paise it paid this time. Lakhan's version compiles with warnings, but pays nobody: every bill stays unpaid and it returns 0. Fix it, keeping its name and types.

    The Check gives it bills of F10122 21084 paise (unpaid), F10113 0 (unpaid), F10150 9120 (paid) and F10018 14542 (unpaid): it must return 35626, and afterwards the paid fields must be true, false, true, true. Called again on the same bills, it must return 0. For two unpaid bills of 500 and 77 paise it must return 577 and mark both paid.

    Farhan will ask: why did the map never run, and why did the compiler only warn instead of refusing to build?

What you will learn

  • Closures: |fat| fat >= min_fat, a function without a name that can use the variables around it.
  • Capturing: by reference, by mutable reference, or by value with move.
  • Fn, FnMut and FnOnce: the three traits that say how a closure may be called.
  • The Iterator trait: next, which gives Some(item) until it gives None.
  • Adapters and consumers: map, filter, filter_map, enumerate, zip, take, skip, chain, flat_map; then sum, count, min_by_key, max_by_key, fold, any, all, collect.
  • Laziness: an adapter does nothing until a consumer asks.
  • iter, iter_mut and into_iter, and an iterator of your own.

More in Traits and data

Build "Closures and iterators" yourself

DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Rust are free. This one comes with the all labs plan.