Closures and Iterators
Closures and their capture modes, `move`, `Fn`/`FnMut`/`FnOnce`, the `Iterator` trait, adapters and laziness.
13 questions
JuniorTheoryCommonWhat is a closure in Rust, and how does it capture its environment?
What is a closure in Rust, and how does it capture its environment?
A closure is an anonymous function that can use variables of the scope it is written in. Each is captured the weakest way the body needs: &T to read, &mut T to change, by value to move it out; move forces by value.
Common mistakes
- ✗Thinking a closure copies the outer variables at the moment it is created
- ✗Expecting to list the captures by hand, as in a C++ lambda
- ✗Believing every closure must be bound with
let mut, not only one that changes a capture
Follow-up questions
- →Why does a closure that changes a captured variable need
let muton its binding? - →What did edition 2021 change about capturing a single field of a struct?
JuniorTheoryCommonWhat does the program print?
What does the program print?
5 10
Open full question →Common mistakes
- ✗Expecting
12 10, as in Python: the closure keeps thekthat existed when it was written, andlet k = 10adds a new variable instead of changing that one. - ✗Expecting a compile error, as with a nested
fn(E0434): unlike a function, a closure can read the variables of the code around it.
Follow-up questions
- →What happens if
kis declaredmutandlet k = 10;becomesk = 10;? - →How would you write
addwith explicit parameter and return types?
JuniorTheoryCommonWhat does the program print?
What does the program print?
[1, 9, 25]
Open full question →Common mistakes
- ✗Expecting
[4, 16], as iffilterthrew away the numbers its closure accepts: it keeps them, so the odd 1, 3 and 5 go on tomap. - ✗Expecting
[1, 9], as if1..=5stopped before 5: the=makes the range include its end, so 25 is in the result too.
Follow-up questions
- →What does the chain produce if you swap
filterandmap? - →Why does
collectneed the typeVec<i32>written onv?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
1:let mut countis not enough, becauseincstores a mutable reference tocount, and calling it changes the closure, which therefore needslet mut inc. - ✗Expecting the closure to change a copy and print
0: withoutmoveit borrowscountitself, and withlet mut incthe program would print 1.
Follow-up questions
- →Why does a closure that only reads
countnot needmut? - →Which of the traits
Fn,FnMutandFnOncedoesincimplement?
JuniorTheoryCommonWhat does the program print (lines separated by spaces)?
What does the program print (lines separated by spaces)?
start map 1 map 2 6
Open full question →Common mistakes
- ✗Expecting
map 1 map 2beforestart, as from an eagermapin JavaScript: Rust'smaponly wraps the iterator, and its closure runs whensumpulls the elements. - ✗Expecting a compile error because
itis notmut:sumtakes the iterator by value, so the binding itself never changes.
Follow-up questions
- →What would the program print if the line with
sumwere removed? - →In what order would the lines appear with a
filteradded aftermap?
JuniorTheoryCommonHow do Rust iterators work, and why does v.iter().map(f) alone do nothing?
How do Rust iterators work, and why does v.iter().map(f) alone do nothing?
An iterator implements Iterator: its one required method next returns Some(item) until None. Adapters like map and filter just wrap it in a new iterator; nothing runs until a consumer (sum, collect, for) calls next.
Common mistakes
- ✗Expecting
mapto run its closure as soon as the chain is written - ✗Thinking of an iterator as a collection with indices rather than a source of
nextcalls - ✗Ignoring the compiler's
unused Map that must be usedwarning on a chain with no consumer
Follow-up questions
- →Why does
nexttake&mut self, and what does that mean for aletbinding? - →How can an infinite iterator such as
(1..)be used safely?
MiddleCodeCommonImplement Iterator for a Fibonacci struct and use take, filter and sum on it
Implement Iterator for a Fibonacci struct and use take, filter and sum on it
Keep the state (a, b) in the struct, set type Item = u64 and write only next: return Some(a) and shift to (b, a + b). take, filter and sum are default methods built on next; the even ones among the first 10 sum to 44.
Common mistakes
- ✗Implementing
takeorfilterby hand, though they are default methods built onnext - ✗Buffering the sequence in a
Vec, which throws laziness away and cannot be endless - ✗Forgetting that
a + boverflowsu64on the 93rd call tonextand panics in a debug build
Follow-up questions
- →How would you make
Fibend withNoneinstead of panicking on overflow? - →Why does
for n in Fib::new()work without anIntoIteratorimpl forFib?
MiddleTheoryCommonHow do Fn, FnMut and FnOnce differ, and which bound should a parameter take?
How do Fn, FnMut and FnOnce differ, and which bound should a parameter take?
The body decides: moving a capture out leaves only FnOnce, changing one gives FnMut, only reading gives Fn. Every Fn is also FnMut and FnOnce, so a parameter asks for the loosest bound its calls allow: called once, FnOnce.
Common mistakes
- ✗Deriving the trait from the capture mode, so expecting every
moveclosure to beFnOnce - ✗Reading
Fnas safe to call from several threads, which is the job ofSendandSync - ✗Asking for
FnwhereFnMutorFnOncewould do, which rejects valid closures
Follow-up questions
- →Why does
thread::spawntake anFnOnceclosure whileIterator::maptakesFnMut? - →What does the compiler say when a closure that drops its capture is passed where
Fnis expected?
MiddleTheoryCommonWhat do iter(), iter_mut() and into_iter() yield, and which does for x in v use?
What do iter(), iter_mut() and into_iter() yield, and which does for x in v use?
iter() yields &T, iter_mut() yields &mut T for in-place changes, into_iter() yields T and consumes the collection. for calls into_iter() on what follows in: v moves the vector, &v acts as iter(), &mut v as iter_mut().
Common mistakes
- ✗Using
vafterfor x in v, which moved it into the loop (E0382) - ✗Expecting
into_iter()to clone the elements and leave the vector usable - ✗Believing
for x in &vmoves the vector because the loop callsinto_iter()
Follow-up questions
- →What does
into_iter()yield when it is called on a&Vec<T>, and why? - →Why did
into_iter()on an array change what it yields in edition 2021?
MiddleTheoryCommonWhat does move do on a closure, why do threads need it, and is it then FnOnce?
What does move do on a closure, why do threads need it, and is it then FnOnce?
move makes a closure take every capture by value: Copy values are copied, the rest moved. thread::spawn needs it: its closure must be 'static, as it may outlive the caller. The trait is unchanged: a read-only move closure stays Fn.
Common mistakes
- ✗Expecting a
moveclosure to becomeFnOnceand run only once - ✗Expecting the caller to keep using a non-
Copyvariable aftermovecaptured it - ✗Expecting a
moveclosure to change the caller'si32, though it changes its own copy
Follow-up questions
- →How do you share one
Vecbetween the main thread and a spawned thread? - →Why does
tokio::spawnfrom the async runtime Tokio usually take anasync moveblock?
MiddleCodeOccasionalSum the positive amounts and count the negative ones in one pass with fold
Sum the positive amounts and count the negative ones in one pass with fold
Fold into a tuple: amounts.iter().fold((0, 0), |(total, neg), &a| …), adding a to total if a > 0 and 1 to neg if a < 0. One pass, no buffer; two filter chains read the slice twice, and partition allocates two Vecs.
Common mistakes
- ✗Counting two
filterchains as one pass, though each reads the whole slice again - ✗Using
partitionand counting the secondVec, where the zeros land as well - ✗Reaching for
reduce, whose accumulator must have the element type, not a tuple
Follow-up questions
- →How would
try_foldstop the pass as soon as the total overflowsi64? - →When is a plain
forloop clearer thanfoldfor the same task?
MiddleDebuggingOccasionalFix make_adder and make_op, which return a bare dyn Fn(i32) -> i32 and do not compile
Fix make_adder and make_op, which return a bare dyn Fn(i32) -> i32 and do not compile
A bare dyn Fn has no size known at compile time (E0746). Return impl Fn(i32) -> i32 with move |x| x + k: one hidden type, no allocation. Branches returning different closures need Box<dyn Fn(i32) -> i32>: allocation plus a dynamic call.
Common mistakes
- ✗Thinking
impl Fnlets two branches return different closures - ✗Forgetting
move, so the returned closure borrows the dead parameterk(E0373) - ✗Boxing every returned closure, paying an allocation where
impl Fnwould do
Follow-up questions
- →Why do two closures with identical text in the branches of an
ifstill have different types? - →When would a function pointer type
fn(i32) -> i32work as the return type instead?
SeniorPerformanceOccasionalWhy is an iterator chain usually as fast as a hand-written loop, and when is it slower?
Why is an iterator chain usually as fast as a hand-written loop, and when is it slower?
Adapters are generic structs whose next is monomorphized and inlined: in release, filter().map().sum() becomes one loop with no bounds checks. It loses behind dyn Iterator, in debug builds, or with chunks where chunks_exact drops checks.
Common mistakes
- ✗Expecting each adapter to allocate a buffer or make its own pass over the data
- ✗Benchmarking iterator chains in a debug build, where nothing is inlined
- ✗Hiding a hot chain behind
Box<dyn Iterator>, which turns everynextinto an indirect call
Follow-up questions
- →Why can
for_eachorfoldbeat aforloop over achainof two iterators? - →How would you check that a chain was vectorized, for example in the online compiler explorer Godbolt?