In Rust, how does a closure without `move` decide whether to capture each variable by shared borrow, mutable borrow or by value?
answer
- what the body does decides
- read, write, move out
- weakest mode that works
- captured when the closure is created
basics
~20 sA 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 srustc 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 linesfn 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
Recall the three modes in order, shared borrow, mutable borrow, by value, and that the body's use of each variable picks one.
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.
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.
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.