skip to content

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%

answer

  1. places, not variables
  2. RFC 2229, the 2021 edition
  3. a field of a Drop type
  4. arrays are captured whole

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.

solid answer

~40 s

Under edition 2021 and later, rustc captures a **place**: a variable plus the field accesses the body applies. `|| println!("{}", settings.theme)` stores `&settings.theme`, so `settings.volume += 1` while the closure is live compiles, and `move || settings.theme` moves only that field, leaving `settings.volume` readable. On edition 2018 the same code captured all of `settings` and failed with E0506 and E0382. Precision stops in several places: an array or slice is always captured whole; a packed struct is captured whole; dereferencing an `Rc` captures the `Rc`; and a `move` closure that would move a field out of a type implementing `Drop` captured the whole struct when checked with rustc 1.99.1.

code

rust · 16 lines
rust
struct Settings {
    theme: String,
    volume: u8,
}

fn main() {
    let mut settings = Settings { theme: String::from("dark"), volume: 5 };

    let show_theme = || println!("theme: {}", settings.theme); // captures &settings.theme
    settings.volume += 1;                                      // another field: allowed
    show_theme();

    let take_theme = move || settings.theme;                   // moves settings.theme only
    println!("volume: {}", settings.volume);                   // still readable
    println!("taken: {}", take_theme());
}

go deeper

for a junior

Recall that a modern Rust closure captures the fields it uses, so other fields of the same struct remain usable.

for a middle

Explain place capture with an example that compiles on 2021 and fails on 2018 with E0506, and name the array case.

for a senior

Diagnose the truncation cases, a Drop type, an array, an Rc, packed structs, and explain the drop-order and Send consequences.

for a principal

When moving old crates to a newer edition, weigh which dummy lets protect real destructor or Send behaviour and which can go.

## Places, not variables A **place expression** is something that names a memory location: a variable `settings`, a field `settings.theme`, a tuple element `pair.0`, a dereference `*r`. From the **2021 edition**, stable since **Rust 1.56**, a closure captures the place its body uses rather than the whole variable at the root of it. The proposal was RFC 2229, and the edition guide summarises it as: `|| a.x + 1` now captures only `a.x` instead of `a`. The capture mode rules still apply, per place: reading `settings.theme` captures `&settings.theme`, mutating `settings.volume` captures `&mut settings.volume`, and moving `settings.theme` out captures that field by value. ## What it allows ```rust let show_theme = || println!("theme: {}", settings.theme); // &settings.theme settings.volume += 1; // a different field: allowed show_theme(); let take_theme = move || settings.theme; // moves settings.theme only println!("volume: {}", settings.volume); // still readable ``` On editions 2021 and 2024 this compiles and runs. Compiled with `--edition 2018`, rustc 1.99.1 rejects it twice: ```plaintext error[E0506]: cannot assign to `settings.volume` because it is borrowed error[E0382]: borrow of moved value: `settings.volume` ``` In practice this removes most of the old workarounds, such as `let theme = &settings.theme;` before the closure, which existed only to stop the closure grabbing the whole struct. After the field move, `settings` as a whole is partially moved: its other fields are usable, but the struct itself cannot be passed on. ## Where precision stops The Reference truncates the captured path in specific cases. The ones that come up in real code: | the path goes through | what is captured | |---|---| | an array or slice element, `scores[0]` | the whole array or slice | | a field of a `#[repr(packed)]` struct | the whole struct | | `*rc` for an `Rc` (any `Deref` other than `Box`) | the `Rc` itself | | a dereference of a raw pointer | the pointer, not what it points to | | a union field | the whole union | | a `move` closure going through a reference `&mut t` | the reference itself | Two checks with rustc 1.99.1 on edition 2024 show the effect: - With `let mut scores = [String::new(), String::new()];`, a live closure reading `scores[0].len()` makes `scores[1].push('x')` fail with E0502, cannot borrow `scores[_]` as mutable. - With `impl Drop for Settings`, `move || settings.theme.len()` captured all of `settings`: a field cannot be moved out of a type with a destructor, and the later `println!("{}", settings.volume)` failed with E0382, borrow of moved value: `settings`. A non-`move` closure reading `settings.theme` on the same type still captured only the field. ## Side effects of capturing less The edition guide lists two observable consequences, which is why the change waited for an edition: 1. **Drop order.** A closure that moves `t.0` out of a tuple owns only that element; `t.1` is now dropped when `t` goes out of scope, not when the closure is dropped. 2. **Auto traits.** A closure is `Send`, `Sync`, `Clone` or `UnwindSafe` only if its captured values are. A wrapper `struct Ptr(*mut i32)` with `unsafe impl Send` used to make a `thread::spawn` closure `Send`; with disjoint capture the closure captures `px.0`, a raw pointer, and is no longer `Send`. Writing `let _ = &settings;` at the top of the closure body forces the whole variable to be captured; the edition migration inserts exactly that "dummy let" where the change could matter. How migrations and editions work is covered with editions. ## Common mistakes - Stating that a closure always captures whole variables, which is the edition 2018 rule. - Assuming indexing an array captures only that element. - Assuming `move` on a field of a `Drop` type moves just the field. - Forgetting that a capture change can alter when a destructor runs. ## Reading a capture error on a struct rustc's messages name the captured place, which tells you how precise the capture was. A note such as "borrow occurs due to use in closure" pointing at `settings.theme`, with the conflict reported on `settings.volume` only under `--edition 2018`, means precision is doing its job on the current edition. When the error instead names the whole variable on edition 2024, as in "borrow of moved value: `settings`", look for one of the truncation cases in the table above: - a destructor on the struct, which blocks moving a field out; - an index into an array or slice; - a dereference through `Rc` or another non-`Box` smart pointer; - a packed representation. The usual repair is to bind the needed field to a local before the closure, `let theme = settings.theme.clone();`, and capture that local instead.

  • In Rust 2021 and later, how do you force a closure to capture the whole `settings` variable?
    Put `let _ = &settings;` in the closure body. A wildcard binding of a plain place reads nothing, but `&settings` is an expression that must be evaluated, so it captures the whole variable. The edition migration inserts this line where capturing less could change drop order or auto traits.
  • In Rust 2021, why can disjoint capture make a `thread::spawn` closure stop being `Send`?
    A closure is `Send` only if every captured value is. If `px` is a `Send` wrapper around a raw pointer and the body uses `px.0`, the closure now captures the raw-pointer field, which is not `Send`, instead of the wrapper. Using the wrapper through a method, or `let _ = &px;`, captures the whole wrapper again.

  • A Rust closure always captures the whole variable, even if it uses one field.
  • Indexing scores[0] in a closure captures only that array element.
  • move on a field of a type with a Drop impl moves just that field.
  • Capturing fewer fields can never change program behaviour.
  • Disjoint capture arrived in the 2024 edition.

Assumes edition 2021 or 2024 (Rust 1.56 or later), checked on rustc 1.99.1; a crate still on edition 2018 captures whole variables.