skip to content

Captured Variables

A closure captures variables by shared borrow, mutable borrow or move, choosing the least it needs unless you write move. Interviewers ask what a closure captures and when move is required.

on this pageshow

questions

5

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 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 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

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