Module 14 — Closures & Iterators
Goal
Functional pipelines that compile down to hand-written loops. Fn/FnMut/FnOnce, laziness, adapters, and writing your own iterator.
Start here — what this module is really about
Two features that look like conveniences and are actually the backbone of idiomatic Rust.
A closure is a function you can write inline, which remembers the variables around it.
let threshold = 10;
let is_big = |n: &i32| *n > threshold; // captures `threshold` from the surroundingsA plain function cannot see threshold. A closure can, and it carries what it needs with it. Because Rust tracks ownership, it also has to know how the closure uses those captured values — reading, changing, or taking them — and that is what the three traits Fn, FnMut and FnOnce describe. You rarely name them until you store a closure in a struct or return one.
An iterator is a value that produces a sequence, one item at a time, on demand.
The key word is on demand. This does nothing at all:
let result = numbers.iter().map(|n| n * 2).filter(|n| n > &10);No numbers were doubled. map and filter build a description of work to be done, and it stays undone until something asks for the items — collect(), sum(), or a for loop. That property is called laziness, and it is why you can chain ten adaptors without creating ten intermediate lists.
The reason this matters beyond elegance: the compiler collapses the whole chain down to roughly the loop you would have written by hand. No intermediate allocations, no per-item function call overhead. You get the readable version and the fast version at the same time, which is what people mean when they call Rust's abstractions zero-cost.
The one sentence to remember: closures are functions that carry their surroundings, and iterators are lazy pipelines that compile away to nothing.
Learning objectives
- Write closures and understand how they capture their environment
- Distinguish
Fn,FnMut, andFnOnceand know when each applies - Use
moveclosures correctly - Implement
Iteratorby hand and use the adaptor library fluently - Explain laziness and why iterator chains compile to fast loops
14.1 Closures
Anonymous functions that can capture their environment:
let add_one = |x| x + 1;
let add = |a: i32, b: i32| -> i32 { a + b };
let multiplier = 3;
let times = |x| x * multiplier; // captures `multiplier` from the environment
println!("{}", times(5)); // 15Type annotations are optional because closures are local — the compiler infers from usage. But inference happens once:
let f = |x| x;
let s = f(String::from("hi"));
// let n = f(5); // ❌ f was inferred as |String| -> StringThe three capture modes
| Trait | Captures by | Can be called | Example |
|---|---|---|---|
FnOnce | value (moves) | once | closures that consume a captured value |
FnMut | mutable reference | many times, needs mut | closures that mutate captured state |
Fn | immutable reference | many times | read-only closures |
They form a hierarchy: every Fn is also FnMut, and every FnMut is also FnOnce.
Rust infers the least restrictive mode your body requires.
// Fn — only reads
let list = vec![1, 2, 3];
let print = || println!("{list:?}");
print(); print(); // callable repeatedly, list still usable
println!("{list:?}");
// FnMut — mutates
let mut list = vec![1, 2, 3];
let mut push = |x| list.push(x);
push(4); push(5);
// println!("{list:?}"); // ❌ still mutably borrowed here
drop(push);
println!("{list:?}"); // ✅ after the closure is done
// FnOnce — consumes
let s = String::from("hello");
let consume = move || s; // moves s out
let got = consume();
// consume(); // ❌ can only be called oncemove closures
move forces capture by value, even when a reference would suffice:
use std::thread;
let data = vec![1, 2, 3];
thread::spawn(move || { // required: the thread may outlive `data`'s scope
println!("{data:?}");
}).join().unwrap();
// println!("{data:?}"); // ❌ moved into the closuremove is required whenever the closure outlives the current scope: threads, returned
closures, async tasks, event callbacks.
Closures as parameters and return values
fn apply<F: Fn(i32) -> i32>(f: F, v: i32) -> i32 { f(v) }
fn apply_mut<F: FnMut()>(mut f: F) { f(); f(); }
fn apply_once<F: FnOnce() -> String>(f: F) -> String { f() }
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n // `move` needed: n must outlive the function
}
fn make_boxed(n: i32) -> Box<dyn Fn(i32) -> i32> {
Box::new(move |x| x + n) // when you need to store it in a struct/collection
}
fn main() {
println!("{}", apply(|x| x * 2, 21));
let add5 = make_adder(5);
println!("{}", add5(10));
}Rule: take the loosest bound your function needs. FnOnce accepts the most callers;
Fn the fewest.
Function pointers
fn double(x: i32) -> i32 { x * 2 }
let v: Vec<i32> = vec![1, 2, 3].into_iter().map(double).collect();
let strings: Vec<String> = vec![1, 2, 3].iter().map(ToString::to_string).collect();fn (function pointer) implements all three closure traits, so plain functions can be
passed anywhere a closure is expected. Enum tuple variants are constructor functions too:
vec![1,2].into_iter().map(Some).
Fn, FnMut, FnOnce — what the three really mean
Every closure automatically implements one or more of three traits, decided by what it does with the values it captured — not by anything you write:
let name = String::from("ana");
// Fn — only reads what it captured. Callable many times.
let greet = || println!("hello {name}");
greet(); greet();
// FnMut — changes what it captured. Callable many times, needs `mut`.
let mut count = 0;
let mut tick = || count += 1;
tick(); tick();
// FnOnce — consumes what it captured. Callable exactly once.
let consume = move || drop(name);
consume();
// consume(); // ❌ the captured String is goneThe mental shortcut: the trait describes what the closure needs from its captured environment. Reading is Fn, modifying is FnMut, taking is FnOnce. Every Fn is also an FnMut and an FnOnce, so requiring Fn is the strictest demand and requiring FnOnce is the loosest.
And move: writing move || forces the closure to take ownership of everything it captures rather than borrowing. You need it whenever the closure outlives the current scope — spawning a thread (module 17), storing it in a struct, returning it. If you see "closure may outlive the current function", move is the answer the compiler is looking for.
Analogy — the note that remembers the room
A function is a set of instructions that works anywhere. A closure is a note written in a particular room, referring to what was on the table at the time — and it carries that context with it when you hand it on. Fn, FnMut and FnOnce are simply how much the note is allowed to do with the room's contents: look at it, rearrange it, or take it away.
14.2 The Iterator trait
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// ~75 provided methods built on next()
}Implement next, get everything else free:
struct Fib { a: u64, b: u64 }
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let out = self.a;
self.a = self.b;
self.b = out + self.b;
Some(out)
}
}
fn main() {
let f = Fib { a: 0, b: 1 };
let first10: Vec<u64> = f.take(10).collect();
println!("{first10:?}"); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
}Laziness
let v = vec![1, 2, 3];
let iter = v.iter().map(|x| { println!("processing {x}"); x * 2 });
println!("nothing has happened yet");
let result: Vec<i32> = iter.collect(); // NOW it runsAdaptors build a chain of structs; nothing executes until a consumer pulls values.
This is why .map() alone triggers an unused_must_use warning.
The three iterator sources
let v = vec![String::from("a")];
v.iter() // Iterator<Item = &String> — borrow
v.iter_mut() // Iterator<Item = &mut String> — mutable borrow
v.into_iter() // Iterator<Item = String> — consumeLaziness, and the warning that catches everyone
This is the single most common surprise in the module:
let numbers = vec![1, 2, 3];
numbers.iter().map(|n| println!("{n}")); // prints NOTHINGand the compiler tells you so:
warning: unused `Map` that must be used
note: iterators are lazy and do nothing unless consumedmap returned a Map — a value describing work — and nobody asked it for anything, so nothing ran. Three ways to actually consume it:
for n in numbers.iter().map(|n| n * 2) { } // a for loop drives it
let doubled: Vec<i32> = numbers.iter().map(|n| n * 2).collect();
let total: i32 = numbers.iter().map(|n| n * 2).sum();Alongside that, the three ways to start a chain, which is really module 04 wearing different clothes:
| Starter | Yields | The collection afterwards |
|---|---|---|
.iter() | &T — borrowed items | Still yours, unchanged |
.iter_mut() | &mut T — modifiable items | Still yours, modified in place |
.into_iter() | T — owned items | Consumed and gone |
Nearly every "value moved" error in iterator code is into_iter() where iter() was meant — including implicitly, since for x in collection calls into_iter() for you.
Analogy — the conveyor belt that only moves when you pull
An iterator is a conveyor belt that stays perfectly still until someone at the far end asks for the next item. Every adaptor you chain on — map, filter, take — is another station bolted to the belt, and nothing whatsoever happens until a consumer at the end starts pulling. That is why a chain with no collect or for is a compiler warning about work you asked for and never requested.
14.3 The adaptor toolkit
Transforming
.map(|x| x * 2) // transform each element
.filter(|x| *x > 3) // keep matching (note: predicate gets &Item)
.filter_map(|s| s.parse::<i32>().ok()) // filter + map in one; drops None
.flat_map(|s| s.chars()) // map then flatten
.flatten() // Vec<Vec<T>> -> T; also unwraps Option/Result
.enumerate() // (index, item)
.zip(other) // pairs, stops at the shorter
.chain(other) // concatenate iterators
.rev() // reverse (needs DoubleEndedIterator)
.skip(2) .take(3)
.skip_while(|x| *x < 3) .take_while(|x| *x < 8)
.step_by(2)
.peekable() // adds .peek()
.scan(0, |acc, x| { *acc += x; Some(*acc) }) // running state
.windows(2) // (on slices) overlapping pairs
.chunks(3) // (on slices) non-overlapping groups
.inspect(|x| println!("saw {x:?}")) // debugging without changing the chainConsuming
.collect::<Vec<_>>() // also HashMap, String, Result<Vec<_>, E>, ...
.sum::<i32>() .product::<i32>()
.count() .last() .nth(3)
.min() .max() .min_by_key(|x| ..) .max_by(|a, b| ..)
.fold(0, |acc, x| acc + x) // general reduction with an initial value
.reduce(|a, b| a.max(b)) // fold using the first element as the seed
.any(|x| x > 5) .all(|x| x > 0) // short-circuit
.find(|x| **x > 3) .position(|x| x == 3)
.for_each(|x| println!("{x}"))
.partition(|x| x % 2 == 0) // -> (Vec<T>, Vec<T>)
.unzip() // Vec<(A, B)> -> (Vec<A>, Vec<B>)Realistic pipelines
#[derive(Debug)]
struct Employee { name: String, dept: String, salary: u32 }
fn main() {
let staff = vec![
Employee { name: "Ada".into(), dept: "Eng".into(), salary: 120 },
Employee { name: "Alan".into(), dept: "Eng".into(), salary: 110 },
Employee { name: "Grace".into(), dept: "Sales".into(), salary: 95 },
];
// total payroll
let total: u32 = staff.iter().map(|e| e.salary).sum();
// names of engineers, sorted
let mut eng: Vec<&str> = staff.iter()
.filter(|e| e.dept == "Eng")
.map(|e| e.name.as_str())
.collect();
eng.sort();
// group by department
use std::collections::HashMap;
let mut by_dept: HashMap<&str, Vec<&str>> = HashMap::new();
for e in &staff {
by_dept.entry(&e.dept).or_default().push(&e.name);
}
// highest paid
let top = staff.iter().max_by_key(|e| e.salary);
println!("{total} {eng:?} {by_dept:?} {top:?}");
}collect is remarkably flexible
let v: Vec<i32> = (1..5).collect();
let s: String = vec!['a', 'b'].into_iter().collect();
let m: HashMap<&str, i32> = vec![("a", 1), ("b", 2)].into_iter().collect();
let set: HashSet<i32> = vec![1, 2, 2, 3].into_iter().collect();
let r: Result<Vec<i32>, ParseIntError> = vec!["1", "2"].iter().map(|s| s.parse()).collect();
let o: Option<Vec<i32>> = vec![Some(1), Some(2)].into_iter().collect();The last two are the magic ones: an iterator of Results collects into a Result of a
collection, short-circuiting on the first error.
14.4 Performance
Iterator chains are zero-cost. This:
let sum: u64 = (0..1_000_000).filter(|x| x % 3 == 0).map(|x| x * x).sum();compiles to essentially the same machine code as a hand-written loop — often better, because the compiler knows the bounds and can elide bounds checks and auto-vectorize.
Two practical notes:
- Prefer iterators over index loops for both clarity and speed.
collect()allocates. Chaining.collect()mid-pipeline just to call another adaptor wastes an allocation; keep the chain lazy until the end.
Analogy — the abstraction that leaves no trace
In most languages a chain of map/filter is a stack of function calls building throwaway lists at each step — elegance you pay for in cycles. Rust compiles the whole chain down to roughly the loop you would have written by hand. Zero-cost abstraction is not marketing here: read the assembly and the stations on the belt have vanished.
Jargon buster
Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.
| Term | In plain English |
|---|---|
| closure | An inline function that captures variables from where it was written. |
| capture | Taking a surrounding variable into the closure, by reference or by value. |
move | Forcing a closure to take ownership of everything it captures. |
Fn / FnMut / FnOnce | Traits describing whether a closure reads, changes or consumes what it captured. |
| iterator | A value producing items one at a time via next(). |
| lazy | Doing no work until something asks for an item. |
| adaptor | An iterator method returning another iterator: map, filter, take, zip. |
| consumer | A method that drives the iterator to completion: collect, sum, for_each, count. |
collect() | Gathering an iterator's items into a collection — the target type decides what you get. |
| turbofish | collect::<Vec<_>>() — naming the collection type at the call site. |
| zero-cost abstraction | A construct that compiles to the same machine code as the hand-written version. |
If you get stuck
The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.
| What you see | What it means | What to do |
|---|---|---|
warning: unused Map that must be used | You built a pipeline and never consumed it. | Add .collect(), .sum(), for_each, or drive it with a for loop. |
error[E0282]: type annotations needed on collect() | collect can build many types; the compiler cannot guess which. | Annotate the binding (let v: Vec<i32> = ...) or use the turbofish. |
closure may outlive the current function | The closure borrows something that will be gone. | Add move before the ` |
error[E0382]: use of moved value after a for loop | The loop called into_iter() and consumed the collection. | Iterate over &collection, or use .iter(). |
cannot borrow as mutable inside a closure | The closure is FnMut but the binding is not mut. | `let mut f = |
Now make it stick: work through the drills for this module, then carry on to Module 15 — Smart Pointers & Interior Mutability.
