FerrousPath

Level 2 · Practitioner· Lesson 4 of 8 · 30 min

Closures and iterators

Anonymous functions that capture their environment, the three Fn traits, and lazy iterator pipelines that compile down to tight loops.

Closures

A closure is an anonymous function that can use variables from the scope where it is defined.

fn main() {
    let factor = 3;
    let scale = |x: i32| x * factor; // captures `factor` by reference
    println!("{}", scale(14));

    let mut log = Vec::new();
    let mut record = |msg: &str| log.push(msg.to_string()); // captures `log` mutably
    record("start");
    record("stop");
    println!("{log:?}");
}

Parameter and return types are usually inferred. Each closure has its own unique, unnameable type, which is why you accept closures through generics.

Fn, FnMut, FnOnce

The compiler captures each variable in the least restrictive way the body allows, and that determines which traits the closure implements:

Trait The closure… Can be called
Fn only reads its captures many times, even concurrently
FnMut mutates its captures many times, needs &mut
FnOnce consumes its captures once

Every Fn is also FnMut, and every FnMut is also FnOnce. So when writing a function that takes a closure, ask for the weakest trait you can — FnOnce if you call it once, FnMut if several times, Fn only if you need shared calls.

fn apply_twice<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
    f(f(x))
}

fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n // `move`: take ownership of n so the closure can outlive this function
}

fn make_counter() -> impl FnMut() -> u32 {
    let mut count = 0;
    move || {
        count += 1;
        count
    }
}

fn main() {
    println!("{}", apply_twice(|x| x * x, 3));
    let add5 = make_adder(5);
    println!("{}", add5(10));
    let mut next = make_counter();
    println!("{} {} {}", next(), next(), next());

    let name = String::from("Ferris");
    let consume = move || name; // returns the captured String: FnOnce
    println!("{}", consume());
    // consume(); // ❌ already called once
}

The Iterator trait

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
    // …plus about 75 provided methods built on next()
}

Implement one method and you receive everything else:

struct Fibonacci { a: u64, b: u64 }

impl Iterator for Fibonacci {
    type Item = u64;
    fn next(&mut self) -> Option<u64> {
        let out = self.a;
        self.a = self.b;
        self.b += out;
        Some(out)
    }
}

fn main() {
    let fib = Fibonacci { a: 0, b: 1 };
    let evens: Vec<u64> = fib
        .filter(|n| n % 2 == 0)
        .take_while(|&n| n < 1000)
        .collect();
    println!("{evens:?}");
}

That iterator is infinite, and it is fine, because iterators are lazy: adapters describe work, and nothing happens until a consumer asks for items.

Three ways to iterate a collection

Call Yields Collection afterwards
v.iter() or for x in &v &T still usable
v.iter_mut() or for x in &mut v &mut T still usable
v.into_iter() or for x in v T consumed

A working vocabulary

fn main() {
    let words = vec!["apple", "bob", "cherry", "dad", "elderberry"];

    // Adapters: lazy, return another iterator.
    let long: Vec<String> = words
        .iter()
        .filter(|w| w.len() > 3)
        .map(|w| w.to_uppercase())
        .collect();
    println!("{long:?}");

    // Consumers: drive the iterator and produce a value.
    let total: usize = words.iter().map(|w| w.len()).sum();
    let longest = words.iter().max_by_key(|w| w.len());
    let has_palindrome = words.iter().any(|w| w.chars().eq(w.chars().rev()));
    let position = words.iter().position(|&w| w == "cherry");
    println!("{total} {longest:?} {has_palindrome} {position:?}");

    // fold: the general accumulator.
    let sentence = words.iter().fold(String::new(), |mut acc, w| {
        if !acc.is_empty() { acc.push(' '); }
        acc.push_str(w);
        acc
    });
    println!("{sentence}");

    // Combining iterators.
    for (i, (a, b)) in words.iter().zip(words.iter().skip(1)).enumerate() {
        println!("{i}: {a} → {b}");
    }
    let nested = vec![vec![1, 2], vec![], vec![3]];
    let flat: Vec<i32> = nested.into_iter().flatten().collect();
    let windows: Vec<i32> = flat.windows(2).map(|w| w[1] - w[0]).collect();
    println!("{flat:?} {windows:?}");
}

collect is generic over its target

use std::collections::{BTreeSet, HashMap};

fn main() {
    let pairs = [("one", 1), ("two", 2), ("three", 3)];
    let map: HashMap<_, _> = pairs.into_iter().collect();
    let set: BTreeSet<char> = "mississippi".chars().collect();
    let joined: String = set.iter().collect();
    println!("{} {joined}", map["two"]);

    // Collecting Results: stop at the first error.
    let good: Result<Vec<i32>, _> = ["1", "2", "3"].iter().map(|s| s.parse::<i32>()).collect();
    let bad: Result<Vec<i32>, _> = ["1", "x", "3"].iter().map(|s| s.parse::<i32>()).collect();
    println!("{good:?}\n{bad:?}");
}

Zero-cost abstraction

An iterator chain is a stack of generic structs, each monomorphized and inlined into the next. After optimisation, xs.iter().map(f).filter(g).sum() typically compiles to the same machine code as the loop you would have written by hand — and sometimes better, because iterating a slice needs no bounds checks. Write the pipeline that reads best.

Exercises

  1. Using only iterator methods, compute the sum of the squares of the odd numbers below 100.
  2. Write fn group_by_len(words: &[&str]) -> HashMap<usize, Vec<String>> with fold or a for loop and the entry API.
  3. Implement an iterator Countdown(u32) that yields n, n-1, …, 1, then use .rev()-free adapters to print only the multiples of 3.
  4. Write fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C.
Solution to 4
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
    move |x| g(f(x))
}

fn main() {
    let inc_then_double = compose(|x: i32| x + 1, |x: i32| x * 2);
    println!("{}", inc_then_double(5));
}

Check your understanding

Pick an answer to see the explanation.

  1. 1.What does v.iter().map(|x| x * 2); do on its own?

  2. 2.A closure that moves a captured String out of itself when called implements which trait?

  3. 3.What does the move keyword do on a closure?

Key terms in this lesson

Finished the lesson and the exercises?