Rust Playbook

Course › Week 3 · Iterators, real data, speed › Day 2 · lesson 16 of 42 · 15 min reading + 60–90 min practice

Iterators

map, filter, collect and fold, lazy by default, and as fast as a hand-written loop.

Iteratormapfiltercollectfold

On this page
  1. 1. An iterator is something with next()
  2. 2. iter, into_iter, iter_mut
  3. 3. map and collect
  4. 4. filter, count, sum
  5. 5. Nothing happens until you ask
  6. 6. enumerate and take
  7. 7. filter_map: parse, and drop what does not parse
  8. 8. Collecting into a map, or into a Result
  9. 9. fold, and the others you will meet
  10. Coming from PHP
  11. Practice
  12. Remember

Most Rust code you will read processes data as a chain: lines.iter().filter(…).map(…).collect(). If you use Laravel collections, you already think this way. What is new is that a Rust chain does no work until the end asks for a result, and that it compiles to the same machine code as the hand-written loop.

One idea per section. Each one replaces a loop you wrote by hand in the first two weeks.

1. An iterator is something with next()

The whole Iterator trait rests on one method: next() returns Some(item), or None when there are no more. A for loop is just a loop that calls next() until it gets None.

src/main.rs
fn main() {
    let nights: Vec<u32> = vec![3, 7];
    let mut items = nights.iter();

    println!("{:?}", items.next());
    println!("{:?}", items.next());
    println!("{:?}", items.next());
}
$ cargo run
Some(3)
Some(7)
None

You met this on Week 2’s Day 3: row.split(',') gave an iterator, and each .next() gave the next field. .lines(), .chars(), .split() and env::args() are all iterators.

2. iter, into_iter, iter_mut

The three ways to iterate a collection are the three ways to use a value (Week 1): borrow it, change it, or take it.

MethodItems areAfterwards the Vec isfor loop equivalent
.iter()&T, borrowedunchanged, still usablefor x in &v
.iter_mut()&mut T, changeablechanged, still usablefor x in &mut v
.into_iter()T, ownedgone: moved into the iteratorfor x in v

Most chains start with .iter(). Use .into_iter() when you are done with the collection and want its items without copying them.

3. map and collect

map turns each item into something else, with a closure. collect gathers the results into a collection. The type of the variable says which collection:

src/main.rs
fn main() {
    let nightly_cents: Vec<u64> = vec![15_010, 18_000, 12_500];

    let with_tax: Vec<u64> = nightly_cents.iter().map(|cents| cents + 500).collect();
    let labels: Vec<String> = with_tax
        .iter()
        .map(|cents| format!("{cents} cents"))
        .collect();

    println!("{with_tax:?}");
    println!("{labels:?}");
}
$ cargo run
[15510, 18500, 13000]
["15510 cents", "18500 cents", "13000 cents"]

collect needs to know what to build

collect can build a Vec, a HashMap, a String, and more. Without a type to aim at, the compiler asks:

src/main.rsdoes not compile
fn main() {
    let nightly_cents: Vec<u64> = vec![15_010, 18_000, 12_500];

    let with_tax = nightly_cents.iter().map(|cents| cents + 500).collect();
    println!("{with_tax:?}");
}
cargo build
error[E0283]: type annotations needed
 --> src/main.rs:4:9
  |
4 |     let with_tax = nightly_cents.iter().map(|cents| cents + 500).collect();
  |         ^^^^^^^^                                                 ------- type must be known at this point
  |
  = note: the type must implement `FromIterator<u64>`
note: required by a bound in `collect`
 --> /rustc/20ddd01716a87c0fcf06ae4752d85a4abc15bcdf/library/core/src/iter/traits/iterator.rs:2073:4
help: consider giving `with_tax` an explicit type
  |
4 |     let with_tax: Vec<_> = nightly_cents.iter().map(|cents| cents + 500).collect();
  |                 ++++++++

For more information about this error, try `rustc --explain E0283`.
error: could not compile `hello` (bin "hello") due to 1 previous error

Give the variable its type, as above, or write it on collect itself: .collect::<Vec<u64>>(). That ::<…> is called the turbofish; the variable type reads better and is the usual choice.

4. filter, count, sum

filter keeps the items for which the closure returns true. count and sum consume the iterator and give one number.

src/main.rs
fn main() {
    let lines = [
        "[2026-11-30 09:41:03] production.ERROR: Deadlock found",
        "#0 /var/www/app/Actions/ConfirmBooking.php(41)",
        "[2026-11-30 09:41:04] production.INFO: Booking confirmed",
        "[2026-11-30 11:30:12] production.ERROR: cURL error 28",
        "[stacktrace]",
        "[2026-11-30 12:00:00] production.CRITICAL: Queue worker stopped",
    ];

    let entries = lines.iter().filter(|line| line.starts_with("[20")).count();
    let errors = lines.iter().filter(|line| line.contains(".ERROR:")).count();
    let total_cents: u64 = [15_010, 15_010, 18_000].iter().sum();

    println!("{entries} entries, {errors} errors, {total_cents} cents");
}
$ cargo run
4 entries, 2 errors, 48020 cents

Week 2’s checkpoint ended with a hand-written total loop and the promise that it becomes prices.iter().sum(). Here it is. sum needs a type to add into, like collect, so total_cents has one.

In filter(|line| …), line is a &&&str: a reference to an item of iter(), which is itself a &str. Method calls see through any number of &, so you rarely notice.

5. Nothing happens until you ask

map and filter are adapters: they build a new iterator and do no work. Only a consumer (collect, count, sum, a for loop) pulls the items through. A chain with no consumer does nothing, and the compiler warns you:

src/main.rs
fn main() {
    let ids: Vec<u64> = vec![5521, 5522, 5523];

    ids.iter()
        .map(|id| println!("sending reminder for booking {id}"));

    println!("done");
}
cargo build
warning: `Iterator::map` call that discard the iterator's values
 --> src/main.rs:5:10
  |
5 |         .map(|id| println!("sending reminder for booking {id}"));
  |          ^^^^--------------------------------------------------^
  |          |   |
  |          |   this function returns `()`, which is likely not what you wanted
  |          |   called `Iterator::map` with callable that returns `()`
  |          after this call to map, the resulting iterator is `impl Iterator<Item = ()>`, which means the only information carried by the iterator is the number of items
  |
  = note: `Iterator::map`, like many of the methods on `Iterator`, gets executed lazily, meaning that its effects won't be visible until it is iterated
  = note: `#[warn(map_unit_fn)]` (part of `#[warn(unused)]`) on by default
help: you might have meant to use `Iterator::for_each`
  |
5 -         .map(|id| println!("sending reminder for booking {id}"));
5 +         .for_each(|id| println!("sending reminder for booking {id}"));
  |

warning: unused `Map` that must be used
 --> src/main.rs:4:5
  |
4 | /     ids.iter()
5 | |         .map(|id| println!("sending reminder for booking {id}"));
  | |________________________________________________________________^
  |
  = note: iterators are lazy and do nothing unless consumed
  = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
help: use `let _ = ...` to ignore the resulting value
  |
4 |     let _ = ids.iter()
  |     +++++++
$ cargo run
done

Not a single reminder was printed. Laziness is what makes long chains cheap: in lines.filter(…).map(…).take(10), each line goes through the whole chain one at a time, nothing is collected in between, and reading stops after the tenth result, even on a 1.4 GB log.

For side effects, like sending a reminder, use a for loop; the first warning suggests for_each, which does the same thing. Use chains to compute values.

6. enumerate and take

enumerate pairs each item with its position, counted from 0 (logstat v2 used it for line numbers). take(n) stops after n items, skip(n) jumps over n.

src/main.rs
fn main() {
    let lines = [
        "[2026-11-30 09:41:03] production.ERROR: Deadlock found",
        "#0 /var/www/app/Actions/ConfirmBooking.php(41)",
        "[2026-11-30 09:41:04] production.INFO: Booking confirmed",
        "[2026-11-30 11:30:12] production.ERROR: cURL error 28",
        "[stacktrace]",
        "[2026-11-30 12:00:00] production.CRITICAL: Queue worker stopped",
    ];

    for (index, line) in lines.iter().enumerate().skip(1).take(3) {
        println!("line {}: {line}", index + 1);
    }
}
$ cargo run
line 2: #0 /var/www/app/Actions/ConfirmBooking.php(41)
line 3: [2026-11-30 09:41:04] production.INFO: Booking confirmed
line 4: [2026-11-30 11:30:12] production.ERROR: cURL error 28

Order matters: enumerate before skip keeps the original line numbers. Swap them and the numbering starts again at 0 after the skip.

7. filter_map: parse, and drop what does not parse

The most useful adapter for logs. The closure returns an Option: Some(value) keeps the value, None drops the item. Parsing and filtering in one step, and since most parsers already return Option, often with no closure body at all:

src/main.rs
fn level_of(line: &str) -> Option<&str> {
    let rest = line.strip_prefix('[')?;
    let (_, rest) = rest.split_once("] ")?;
    let (head, _) = rest.split_once(": ")?;
    let (_, level) = head.rsplit_once('.')?;
    Some(level)
}

fn main() {
    let lines = [
        "[2026-11-30 09:41:03] production.ERROR: Deadlock found",
        "#0 /var/www/app/Actions/ConfirmBooking.php(41)",
        "[2026-11-30 09:41:04] production.INFO: Booking confirmed",
        "[2026-11-30 11:30:12] production.ERROR: cURL error 28",
        "[stacktrace]",
        "[2026-11-30 12:00:00] production.CRITICAL: Queue worker stopped",
    ];

    let levels: Vec<&str> = lines.iter().filter_map(|line| level_of(line)).collect();
    println!("{levels:?}");
}
$ cargo run
["ERROR", "INFO", "ERROR", "CRITICAL"]

Logstat’s whole “is this an entry?” logic, as one line of the chain. Stack-trace lines return None and simply disappear.

8. Collecting into a map, or into a Result

Pairs collect into a HashMap

src/main.rs
use std::collections::BTreeMap;

fn main() {
    let rates = [("Nyhavn flat", 15_010), ("Aarhus loft", 12_500)];

    let by_name: BTreeMap<&str, u64> = rates.into_iter().collect();
    println!("{by_name:?}");
}
$ cargo run
{"Aarhus loft": 12500, "Nyhavn flat": 15010}

Results collect into one Result

Collecting an iterator of Results into Result<Vec<T>, E> gives Ok with every value, or the first error, and stops reading there. One line for “parse all of these, or tell me what was wrong”:

src/main.rs
use std::num::ParseIntError;

fn parse_all(inputs: &[&str]) -> Result<Vec<u32>, ParseIntError> {
    inputs.iter().map(|input| input.trim().parse()).collect()
}

fn main() {
    println!("{:?}", parse_all(&["3", " 7", "2"]));
    println!("{:?}", parse_all(&["3", "seven", "2"]));
}
$ cargo run
Ok([3, 7, 2])
Err(ParseIntError { kind: InvalidDigit })

Use this when one bad value should reject the whole batch, like a form. When bad rows should be reported and skipped, like a CSV import, you want the opposite: Day 4.

9. fold, and the others you will meet

fold is the general form of sum: start with a value, and combine each item into it. PHP calls it array_reduce.

src/main.rs
fn main() {
    let nights: Vec<u32> = vec![3, 7, 2, 14];

    let longest = nights.iter().fold(0, |best, &n| best.max(n));
    let any_month = nights.iter().any(|&n| n >= 28);
    let first_week = nights.iter().position(|&n| n >= 7);

    println!("longest {longest}, any month-long: {any_month}, first week-long at {first_week:?}");
}
$ cargo run
longest 14, any month-long: false, first week-long at Some(1)

|&n| takes the &u32 apart in the parameter itself, like for &nights in yesterday. Use the specific method when one exists (max, any, position); reach for fold when none fits.

MethodGivesPHP / Laravel
mapeach item changedarray_map, ->map()
filteritems that passarray_filter, ->filter()
filter_mapparsed items, failures dropped->map()->filter()
collecta Vec, HashMap, String…->all(), ->toArray()
sum, count, max, minone number (max / min: an Option)->sum(), ->count(), ->max()
any, alla bool->contains(), ->every()
find, positionthe first match (an Option)->first(fn), ->search()
foldanything, built item by itemarray_reduce, ->reduce()
take, skip, enumerate, rev, chain, zipa reshaped iterator->take(), ->skip(), ->reverse(), ->merge(), ->zip()

Coming from PHP

The same chain in a Laravel collection, and the real difference:

errors.php
<?php

$levels = collect(file('storage/logs/laravel.log'))     // the whole file in memory first
    ->map(fn (string $line) => levelOf($line))           // a full new array
    ->filter()                                           // another full array
    ->countBy();

Each Laravel step builds a complete new array before the next one starts. Rust’s steps are lazy, so each line goes through the whole chain and is gone, with no array in between. (Laravel’s LazyCollection works like Rust here, and is exactly what you would reach for with a 1.4 GB file.) And because the compiler sees the whole chain, the result runs as fast as the loop you would have written by hand.

PracticeThe Book ch. 13.2–13.4, Rustlings iterators, and rewrite your loops

Read chapter 13.2 to the end of chapter 13.

In Rustlings: 18_iterators.

Exercise: logstat with iterators

In logstat v2, rewrite Report::top with iterators: start from self.messages.iter(), map each entry to the (Level, &str, u64) triple, collect into a Vec, then sort and truncate as before. Then write one more function, fn levels_seen(lines: &[&str]) -> Vec<&str>, that returns each level that appears at least once, in the order first seen, using filter_map and a check with contains before pushing. Run cargo test after each change.

Show a solution for top
src/report.rs (part)
    pub fn top(&self, n: usize) -> Vec<(Level, &str, u64)> {
        let mut ranked: Vec<(Level, &str, u64)> = self
            .messages
            .iter()
            .map(|((level, message), count)| (*level, message.as_str(), *count))
            .collect();
        ranked.sort_by(|a, b| b.2.cmp(&a.2).then(a.1.cmp(b.1)));
        ranked.truncate(n);
        ranked
    }

The closure’s parameter takes each (&(Level, String), &u64) apart right in the pipes: |((level, message), count)|. The behaviour is identical, so the existing ranks_messages test proves the rewrite.

Remember

  • Adapters (map, filter) do nothing until a consumer (collect, sum, for) pulls the items through.
  • filter_map parses and drops failures in one step; collecting into Result<Vec<_>, _> stops at the first error.

Tomorrow: serde, Rust’s json_encode and json_decode, typed.