skip to content

Iterators and Closures

Iterator chains and closures are how idiomatic Rust loops, and they compile to the same code as a hand loop. Interviewers test laziness, the three iteration forms and the Fn traits.

on this pageshow

explore

questions

26

In Rust, how does a closure without `move` decide whether to capture each variable by shared borrow, mutable borrow or by value?

level: juniorimportance: must knowfreq 74%

answer

  1. what the body does decides
  2. read, write, move out
  3. weakest mode that works
  4. captured when the closure is created

basics

~20 s

A Rust closure without move inspects what its body does with each outside variable: reading it takes a shared borrow, mutating it takes a mutable borrow, and moving it out captures it by value. rustc picks the weakest mode that works.

solid answer

~40 s

rustc infers a capture mode for every outside place the body mentions, and it uses the first mode that fits how the body uses it: shared borrow, then mutable borrow, then by value. `|| println!("{title}")` captures `&title`; `|| clicks += 1` captures `&mut clicks`; `|| drop(title)` captures `title` by value, so the `String` moves into the closure the moment the closure is created and a later `println!("{title}")` fails with E0382. The mode depends only on the body, never on how long the closure lives. A `Copy` value the body uses by value is still captured by shared borrow. Parameter types are inferred too, but only once: after `id(String::new())`, calling `id(5)` is E0308.

code

rust · 17 lines
rust
fn main() {
    let title = String::from("Settings");
    let mut clicks = 0;

    let show = || println!("window: {title}"); // reads title: captures &title
    show();
    println!("still usable: {title}");         // a shared borrow allows other reads

    let mut on_click = || clicks += 1;          // writes clicks: captures &mut clicks
    on_click();
    on_click();
    println!("clicks = {clicks}");              // fine: on_click is never used again

    let close = || drop(title);                 // moves title: captures it by value
    close();
    // println!("{title}");                     // E0382: borrow of moved value: `title`
}

go deeper

for a junior

Recall the three modes in order, shared borrow, mutable borrow, by value, and that the body's use of each variable picks one.

for a middle

Explain that the capture is taken when the closure is created, that a mutable capture needs a let mut binding, and why a by-value capture causes E0382 later.

for a senior

Read rustc's notes, borrow occurs due to use in closure versus value moved into closure here, to say what was inferred, and know the Copy and wildcard exceptions.

for a principal

Use inference as the default in review and ask for move only where a closure must own its captures, so ownership reads off the code.

## What a closure captures A **closure** is an anonymous function value written `|params| body`. Unlike an `fn` item, it can use local variables from the scope it is written in; using one is called **capturing** it. The closure value stores what it captured, so the compiler has to decide, for each variable, *what* to store: a shared reference, a mutable reference, or the value itself. The Reference calls these the **capture modes**. Without the `move` keyword, rustc infers the mode separately for every place the body mentions, and it chooses "the first mode that is compatible with how the captured value is used inside the closure body": 1. **Shared borrow** (`&T`) when the body only reads the place. 2. **Mutable borrow** (`&mut T`) when the body assigns to it or calls a `&mut self` method on it. 3. **By value** when the body moves the value out, for example by passing a `String` to a function that takes it by value or returning it. The Reference also lists a fourth, internal mode, the **unique immutable borrow**, which rustc uses when the body writes through a captured `&mut` reference; it cannot be written in source and, like a mutable borrow, it must be unique. The Reference adds that the mode "is not affected by the code surrounding the closure, such as the lifetimes of involved variables or fields, or of the closure itself". rustc never upgrades a capture to by value because the closure happens to be stored somewhere long-lived; that is what `move` is for. ## The three modes side by side | body does | captured as | what the enclosing code can still do | |---|---|---| | `println!("{title}")` | `&title` | read `title`, but not mutate or move it while the closure is live | | `clicks += 1` | `&mut clicks` | nothing with `clicks` until the closure's last use | | `drop(title)` | `title` by value | nothing: `title` has moved into the closure | Two consequences follow from the table: - A closure that captures by mutable borrow must itself be bound with `let mut`, because calling it needs mutable access to the closure value (rustc reports E0596 otherwise). - A closure that captures by value takes the value **when the closure expression is evaluated**, not when it is called. Even if `close` is never called, `title` is already gone. ## Copy values and places the body never reads Two rules surprise people: - **`Copy` values used by value are borrowed.** The Reference says values that implement `Copy` and are moved inside a non-`move` closure are captured by shared borrow: `let y = x;` inside the body, with `x: [i32; 1024]`, stores a `&x`, and copies out of it on each call. - **A wildcard binding does not capture.** `let _ = x;` does not read `x`, so the closure does not capture it at all, and `x` can still be moved afterwards. ## Parameter and return types are inferred once Closure parameters may carry annotations (`|x: i32| -> i32 { x + 1 }`; a return type forces a block body), but usually rustc infers them from use. A closure is **not generic**: rustc fixes one concrete type for each parameter from the first call it sees. ```rust let id = |x| x; let s = id(String::from("ok")); let n = id(5); // E0308: expected `String`, found integer ``` rustc 1.99.1 reports E0308 with the note "expected because the closure was earlier called with an argument of type `String`". If a closure is never called and nothing else fixes its parameter types, rustc asks for annotations instead. ## Reading the capture from the error When the inferred mode conflicts with code outside, rustc says which capture caused it: "borrow occurs due to use in closure" for a borrow, "value moved into closure here" for a by-value capture. Those two phrases are the fastest way to see what rustc inferred. ## A worked example Picture a settings window in a UI event system. A `show` closure prints the window title, an `on_click` closure counts presses, and a `close` closure hands the title to a function that consumes it. Written without `move`, rustc gives them three different captures from the same scope: - `show` stores `&title`, so the code around it may keep reading `title` while `show` is live. - `on_click` stores `&mut clicks`, so nothing else may touch `clicks` until `on_click` is used for the last time. - `close` stores `title` itself, so after the line that creates `close`, the name `title` refers to a moved-from variable. Nothing in the source says which mode each closure got; the body decides, which is why reviewing a closure means reading what its body does with every outside name. ## Common mistakes - Assuming a closure copies everything it uses when it runs. It captures when it is created, by reference unless the body needs more. - Assuming every capture is by value, as if `move` were the default. - Expecting `|x| x` to accept a `String` and an integer like a generic function. - Forgetting that a by-value capture moves the variable even if the closure is never called.

  • In Rust, is a by-value capture taken when the closure is created or when it is called?
    When it is created. Evaluating the closure expression builds the closure value, and its captures are stored in it then. A closure whose body calls `drop(title)` has already moved `title` out of the enclosing scope even if nobody ever calls it, so any later use of `title` is E0382.
  • In Rust, does a closure whose body is `let _ = report;` capture `report`?
    No. A wildcard pattern does not read the place, and closures only capture places that are read, so `report` is not captured and can still be moved after the closure is written. `let _ = &report;` is different: it evaluates a borrow, so it does capture.
  • In Rust, how do you fix a closure's parameter type up front instead of relying on the first call?
    Annotate the parameter, `|x: u32| x * 2`, and optionally the return type, `|x: u32| -> u32 { x * 2 }`; with a return type the body must be a block. Passing the closure straight to a function whose bound names the argument type also fixes it.

  • A closure copies every variable it uses each time it is called.
  • Without move, a closure takes ownership of every variable it mentions.
  • A closure that only reads a String moves the String into itself.
  • One closure like |x| x accepts a String on one call and an integer on the next.
  • rustc picks a stronger capture when the closure is stored somewhere long-lived.
open as a page

In Rust, what must you write to turn a struct generating a Fibonacci-like ID sequence into an iterator usable with for, map and take?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Implement Iterator for the struct: declare type Item = u64 and write fn next(&mut self) -> Option<u64>, returning None when the sequence ends. Adapters such as map and take, and for loops, then work with no further code.

open as a page

In Rust, how do `Fn`, `FnMut` and `FnOnce` differ, and how does the compiler decide which of them a closure implements?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Fn is called through &self, FnMut through &mut self and FnOnce by value. Every closure implements FnOnce; one that never moves a captured value out also implements FnMut, and one that also never mutates a capture implements Fn.

open as a page

In Rust, why is a `Vec<Task>` unusable after `for task in tasks { ... }`, and how do you loop without giving it up?

level: juniorimportance: must knowfreq 82%

basics

~20 s

A Rust for loop calls IntoIterator::into_iter on its expression, and for a Vec<Task> passed by value that takes ownership, so the vector is moved and later use is E0382. Loop over &tasks or &mut tasks to borrow it instead.

open as a page

In Rust, why does `lines.iter().map(parse)` on its own run no code, and what makes the chain actually execute?

level: juniorimportance: must knowfreq 80%

basics

~20 s

An adapter such as map only wraps the source iterator and the closure in a new struct; no closure runs until a consumer such as collect, sum, count, for_each or a for loop calls next. rustc warns when the chain is dropped unused.

open as a page

In Rust, what does `move` change about a closure's captures, and why does a handler passed to `on_click(f: impl Fn() + 'static)` need it?

level: middleimportance: must knowfreq 72%

basics

~20 s

move makes a Rust closure capture every variable it uses by value: non-Copy values are moved in and Copy values are copied. The closure then owns its captured values instead of borrowing the variables, which a 'static bound such as a stored event handler requires.

open as a page

In a Rust retry helper that calls its operation up to `n` times, should the operation's bound be `Fn`, `FnMut` or `FnOnce`, and why?

level: middleimportance: must knowfreq 65%

basics

~20 s

FnMut. The helper calls the operation more than once, which rules out FnOnce, and FnMut is the loosest bound that allows repeated calls, so callers may pass closures that count attempts or change state. The parameter must be declared mut.

open as a page

For a Rust `Vec<T>`, what does each of `iter()`, `iter_mut()` and `into_iter()` yield, and which `for` loop form matches each one?

level: middleimportance: must knowfreq 74%

basics

~20 s

On a Rust Vec<T>, iter() yields &T, iter_mut() yields &mut T and into_iter() yields owned T while consuming the vector. They match for x in &v, for x in &mut v and for x in v.

open as a page

In Rust, why does `let codes = iter.collect();` fail with E0283, and how does `collect` choose between a Vec, a HashSet and a HashMap?

level: middleimportance: must knowfreq 75%

basics

~20 s

collect is generic over its return type, bounded by FromIterator of the item type, so rustc must learn that type from an annotation, a turbofish or the surrounding code. The chosen type's FromIterator impl decides what gets built.

open as a page

In Rust, why does printing `clicks` between two calls of `let mut on_click = || clicks += 1;` fail with E0502, and what fixes it?

level: middleimportance: should knowfreq 58%

basics

~20 s

The closure stores a &mut clicks from the moment it is created until its last call, so reading clicks in between conflicts with that exclusive borrow. Read after the last call, or have the closure take &mut i32 as a parameter.

open as a page

In Rust, when would you build a paginated API client's record stream with std::iter::from_fn or std::iter::successors instead of a struct implementing Iterator?

level: middleimportance: should knowfreq 40%

basics

~20 s

Use iter::from_fn when a closure holding the cursor can act as next, and iter::successors when each page follows from the previous one. Both return unnameable types behind impl Iterator; a struct wins when callers need extra traits or methods.

open as a page

In Rust, how do you make for v in &tree walk a binary tree in order, and why must the walker carry a lifetime?

level: middleimportance: should knowfreq 40%

basics

~20 s

Implement IntoIterator for &'a Tree<T> with Item = &'a T and IntoIter = Iter<'a, T>, a walker holding a stack of &'a Node<T>. The lifetime ties each yielded reference to the tree, not the walker, so callers can keep them.

open as a page

In Rust, how does Iterator::peekable let you total consecutive paginated records per account, and what do Peekable's peek and next_if return?

level: middleimportance: should knowfreq 45%

basics

~20 s

Calling peekable() wraps an iterator in Peekable, which buffers one item. peek returns Option<&Item> without consuming; next_if(pred) returns Some(item) and consumes it only when the predicate accepts it, otherwise None and the item stays buffered.

open as a page

In Rust, why does `fn min_len(n: usize) -> fn(&str) -> bool { move |s| s.len() >= n }` fail with E0308, and what fixes it?

level: middleimportance: should knowfreq 45%

basics

~20 s

A fn pointer is a bare code address with no room for captured data, so only functions and non-capturing closures coerce to it. This closure captures n, so rustc reports mismatched types. Return impl Fn(&str) -> bool instead.

open as a page

In Rust, when you archive every `Task` from a `Vec<Task>` you keep reusing, why call `tasks.drain(..)` instead of `tasks.into_iter()`?

level: middleimportance: should knowfreq 42%

basics

~20 s

Vec::drain(..) takes &mut self and yields each Task by value while leaving the vector alive, empty and with its buffer, ready for refilling. into_iter() takes self, so it consumes the vector and frees its buffer once the iterator is dropped.

open as a page

When rustc desugars a Rust `for pattern in expr` loop, which calls does it make, and what does that let you write after `in`?

level: middleimportance: should knowfreq 48%

basics

~20 s

rustc turns a for loop into one call to IntoIterator::into_iter(expr) followed by a loop that calls Iterator::next and breaks on None. Anything implementing IntoIterator can follow the in keyword: collections, references to them, ranges, and any iterator, including &mut iter.

open as a page

In Rust, when a `filter` then `map` chain ends in `find`, in what order do the closures run and how many log lines are processed?

level: middleimportance: should knowfreq 58%

basics

~20 s

Item by item: find pulls one line, filter tests it, and only a line that passes reaches map before the next line is pulled. find returns at the first match, so the lines after it are never read by any closure.

open as a page

In Rust, when do you reach for `Iterator::fold` instead of `sum` or `count`, and why can `.sum::<u16>()` panic in a debug build?

level: middleimportance: should knowfreq 55%

basics

~20 s

sum and count produce one number: sum for the type you name, count as a usize. fold carries an accumulator of any type, such as per-service totals in a map. sum panics on overflow when overflow checks are on, as in debug builds.

open as a page

Since Rust's 2021 edition, why can code assign `settings.volume` while a live closure reads `settings.theme`, and when is the whole struct still captured?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Since the 2021 edition (Rust 1.56) a closure captures the exact place it uses, such as settings.theme, not the whole settings variable, so other fields stay free. The whole value is still captured for arrays, packed structs, and moves out of a type that implements Drop.

open as a page

In Rust, why does one `Vec<Button<F>>` reject two buttons built from different closures, and how do you call a closure stored in a field?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Every Rust closure expression has its own unique, anonymous type, so two closures, even identical ones, are two different F types, and one Vec<Button<F>> needs a single F (E0308). Box<dyn FnMut()> lets them mix; call a field as (self.on_click)().

open as a page

In Rust, why do .rev() and .len() fail to compile on a custom ID-block iterator, and what do DoubleEndedIterator and ExactSizeIterator require of it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

rev requires DoubleEndedIterator (E0277 without it) and len exists only on ExactSizeIterator (E0599). Implement next_back for the first; for the second, make size_hint return the exact count and add an empty impl, or the default len panics.

open as a page

In a Rust middleware chain holding `Vec<Box<dyn FnMut(&Event)>>`, why does `for h in &self.handlers { h(e) }` fail with E0596, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Calling an FnMut needs &mut access, but iterating &self.handlers yields shared references, so rustc cannot borrow the handler mutably. Make dispatch take &mut self and use iter_mut, or store Box<dyn Fn> handlers that keep state in Cell, RefCell or a Mutex.

open as a page

In Rust, why does a retry helper that calls its `on_success: G` callback, bounded by `G: FnOnce()`, inside its loop fail with E0382, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Calling an FnOnce moves it, and the loop could reach that call again, so rustc reports use of a moved value. Return or break right after the call, call it once after the loop, or hold it in an Option and take() it.

open as a page

When a Rust function either reads or takes ownership of a batch of `Task`s, when should its parameter be `impl IntoIterator` rather than `&[Task]` or `Vec<Task>`?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Use impl IntoIterator<Item = Task> to consume or Item = &'a Task to read when the body makes one pass: callers may pass a Vec, array, slice, drain or iterator. Use &[Task] for indexing or repeated passes, Vec<Task> for storing.

open as a page

In Rust, how does `Iterator::try_fold` stop a checked total at the first overflow, and why do std's adapters override `try_fold` and `fold`?

level: seniorimportance: should knowfreq 38%

basics

~20 s

try_fold threads an accumulator through a closure returning Option, Result or ControlFlow; the first None, Err or Break is returned at once and the rest stays unread. Adapters override it so work can loop inside each inner iterator.

open as a page

In Rust, what happens when a custom feed iterator's next is called again after it returned None, and what do Iterator::fuse and FusedIterator change?

level: seniorimportance: nice to knowfreq 25%

basics

~10 s

Whatever the iterator's next does: Rust's protocol lets an iterator resume after None. fuse() wraps it so None is final; FusedIterator is a marker promising that already, which turns fuse into a no-op.

open as a page