Closures and Iterators
A closure is an anonymous function written right in place that sees the variables of the surrounding scope. An iterator is a value that yields elements one at a time through its next method. In Rust the two topics go together: almost every iterator method takes a closure, and processing a collection is written as a chain like v.iter().filter(|x| **x > 0).map(|x| x * 2).sum::<i32>() rather than as a loop with indices.
A closure obeys the same ownership rules as the rest of the code. Capturing a variable is a borrow or a move, and the compiler picks the weakest mode that is enough for the body. What the body does with its captures decides which of the Fn, FnMut and FnOnce traits the closure implements, and the trait decides where the closure can be passed. Iterators follow ownership too: iter() lends the elements, iter_mut() lets you change them, into_iter() takes the whole collection.
Iterator adapters are lazy: they do nothing until a consumer such as collect or sum starts asking for elements. That is why a chain creates no intermediate collections, and in a release build compiles to the same loop you would write by hand. This topic walks closures and iterators layer by layer — from closure syntax to lazy evaluation.
Topic map
- Closures — the
|x| x + 1syntax and the full form with types; the first call fixes the parameter types, and a call with another type gives E0308; every closure has its own anonymous type. - Capture Modes — by shared reference, by mutable reference or by value, and the compiler takes the weakest mode; a mutating closure needs
let mut(E0596);moveand threads (E0373); capturing individual fields since edition 2021. - Fn, FnMut and FnOnce — the trait reflects what the body does with its captures, not the capture mode; every
Fnis anFnMut, everyFnMutis anFnOnce;impl Fnversus&dyn FnandBox<dyn Fn>; returning a closure and E0746;fnpointers; async closures. - The Iterator Trait —
type Itemandnext; whatiter,iter_mutandinto_iteryield and whatfor x in &vturns into; your own iterator from a singlenextmethod. - Adapters and Consumers —
map,filter,enumerate,zip,take,skip,chain,flat_map,rev;collectwith a stated type,sum,count,fold,anyandall,find,minandmax. - Lazy Evaluation — without a consumer adapters do nothing, and the compiler warns
iterators are lazy and do nothing unless consumed; the steps of a chain interleave element by element; infinite iterators; the zero cost of chains and where it ends.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Calling a mutating closure declared without mut | error[E0596]: cannot borrow `inc` as mutable, as it is not declared as mutable — the closure holds a mutable reference, and a call changes the closure itself |
Passing a closure without move to thread::spawn | error[E0373]: closure may outlive the current function, but it borrows `data`, which is owned by the current function |
Passing a closure that gives away a captured value where an Fn is expected | error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce` |
Returning a bare dyn Fn or two different closures under one impl Fn | error[E0746]: return type cannot be a trait object without pointer indirection or E0308 with the note no two closures, even if identical, have the same type — you need Box<dyn Fn> |
Using a vector after for x in v | error[E0382]: borrow of moved value: `v` — the loop called into_iter() and took the vector; you need for x in &v |
| Writing a chain of adapters with no consumer | Nothing runs; warning: unused `Map` that must be used with the note iterators are lazy and do nothing unless consumed |
Calling collect() or sum() without a result type | error[E0283]: type annotations needed — you need an annotation let v: Vec<_> or the form collect::<Vec<_>>() |
Why it matters in interviews
Closures and iterators are checked at every level: at junior you are asked to rewrite a loop as a chain and explain iter versus into_iter, at middle — the difference between Fn, FnMut and FnOnce and returning a closure from a function, at senior — what a chain compiles to and when it is slower than a loop. A strong answer rests on ownership: a capture is a borrow or a move, and a closure's trait is decided by what the body does with its captures.
What interviewers usually check:
- What a closure is and in which three ways it captures its environment.
- How
Fn,FnMutandFnOncediffer, how the compiler picks the trait and how the traits nest inside each other. - What
movedoes and why a closure forthread::spawncannot do without it. - How to return a closure from a function:
impl FnversusBox<dyn Fn>. - What
iter,iter_mutandinto_iteryield and how to implementIteratorfor your own type. - Why adapters are lazy and whether a chain is as fast as a hand-written loop.