skip to content

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%

answer

  1. every capture by value
  2. Copy types are copied
  3. 'static means no borrowed locals
  4. E0373 suggests move

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.

solid answer

~40 s

Without `move`, a closure that only reads `theme` stores `&theme`, a borrow of the registering function's local. A bound like `impl Fn() + 'static` rejects that, and rustc reports E0373, closure may outlive the current function, but it borrows `theme`, suggesting `move`. With `move` every capture is by value, so the `String` moves into the closure and nothing points back at the stack frame. Three consequences matter: a moved `String` is unusable outside afterwards (E0382), and two `move` closures need two clones; a `Copy` counter is copied, so `move || clicks += 1` changes the closure's own copy and the outer value stays 0; and moving a reference `r = &theme` moves only the reference, so the closure still borrows `theme`.

code

rust · 20 lines
rust
struct EventBus {
    handlers: Vec<Box<dyn Fn()>>, // Box<dyn Fn()> means Box<dyn Fn() + 'static>
}

impl EventBus {
    fn on_click(&mut self, f: impl Fn() + 'static) {
        self.handlers.push(Box::new(f));
    }
}

fn register(bus: &mut EventBus) {
    let theme = String::from("dark");
    bus.on_click(move || println!("theme: {theme}"));
}

fn main() {
    let mut bus = EventBus { handlers: Vec::new() };
    register(&mut bus);
    for h in &bus.handlers { h(); }
}

go deeper

for a junior

Recall that move makes a closure own what it uses, and that rustc's E0373 help line suggests it.

for a middle

Explain the table: String moved, Copy value copied, reference moved, and why a 'static bound on a stored handler rejects a borrowing closure.

for a senior

Catch the move-on-a-Copy-counter bug in review, clone before moving into several handlers, and know move does not decide the call trait.

for a principal

Decide how handler state is shared in an event API, owned copies, passed-in state or shared ownership, so move closures stay correct.

## What `move` changes A closure written without `move` captures each outside variable in the weakest mode its body allows: shared borrow, mutable borrow, or by value. Writing `move` in front, `move || ...`, overrides that choice. The Reference states that with `move` "all captures are by move or, for Copy types, by copy, regardless of whether a borrow would work". | captured variable | without `move` (body only reads it) | with `move` | |---|---|---| | `theme: String` | `&theme` | `theme` moved in; unusable outside afterwards | | `clicks: i32` (`Copy`) | `&clicks` | a copy of `clicks`; the outside variable stays usable and independent | | `r: &String` | `&r` | the reference `r` copied in; the closure still borrows the `String` | `move` changes only **how** values are captured. It does not change **which** variables are captured, and it does not decide which call trait the closure implements; that depends on what the body does with its captures and is covered with `Fn`, `FnMut` and `FnOnce`. ## Why a stored handler needs it An event system that keeps handlers after the registering function returns has to forbid handlers that borrow that function's locals. The usual way is a `'static` bound: ```rust fn on_click(&mut self, f: impl Fn() + 'static) { self.handlers.push(Box::new(f)); } ``` A type is `'static` when it holds no references that could expire. A closure storing `&theme`, where `theme` is a local of `register`, fails that test, and rustc 1.99.1 reports: ```plaintext error[E0373]: closure may outlive the current function, but it borrows `theme`, which is owned by the current function note: function requires argument type to outlive `'static` help: to force the closure to take ownership of `theme` (and any other referenced variables), use the `move` keyword ``` Adding `move` makes the closure own the `String`, so it is `'static` and the handler can outlive `register`. `std::thread::spawn` demands `'static` for the same reason; that case is covered with `'static` bounds. ## The `Copy` counter trap Because `move` copies `Copy` values, a counter shared this way silently splits in two: - `let mut on_click = move || clicks += 1;` increments the closure's own `i32`. - The outer `clicks` is never touched, so printing it afterwards shows `0`. - rustc 1.99.1 compiles this without a warning, so the bug shows up only at run time. If the handler must update state the rest of the program reads, `move` alone is the wrong tool: pass the state in as a parameter, keep it in a struct the handler owns, or use shared ownership. ## Moving one value into two closures A non-`Copy` value can move only once. Writing `move || println!("a: {theme}")` and then `move || println!("b: {theme}")` fails on the second with E0382, use of moved value. The idiom is to clone before each move: 1. `let theme_a = theme.clone();` 2. `let a = move || println!("a: {theme_a}");` 3. Use `theme` itself in the last closure, or clone again. When the data is large or must stay shared, clone an `Rc` or `Arc` handle instead of the data; how those count owners is covered with smart pointers. ## Moving a reference `move` moves whatever the variable holds. With `let r = &theme;`, `move || println!("{r}")` moves the reference itself, so the closure still borrows `theme` and is not `'static`. `theme` stays readable outside while the closure is live, because both are shared borrows. To make the closure own the data, move an owned value, not a reference to it. ## Common mistakes - Believing `move` makes the closure share the outer variable, so increments become visible outside. - Believing `move` only affects non-`Copy` variables. - Believing a `move` closure can never borrow anything from the enclosing function. - Adding `move` to fix E0373 and then using the moved value again, which trades E0373 for E0382. ## A checklist before writing `move` When a handler is about to be stored, ask three questions about each name its body uses: 1. **Is it a `Copy` value the rest of the program must see change?** Then `move` gives the closure a private copy; pass the state in or keep it in a struct instead. 2. **Is it a non-`Copy` value something else still needs?** Then clone it first and move the clone, or share it through a reference-counted handle. 3. **Is it a reference?** Then `move` copies the reference and the closure stays tied to the borrowed data, so a `'static` bound will still reject it. When all three answers are no, `move` is exactly right: the closure owns what it uses and can outlive the function that built it.

  • In Rust, how do you give two `move` closures the same `theme: String`?
    Clone it before each move, `let theme_a = theme.clone();` then `move || println!("{theme_a}")`, and let the last closure take `theme` itself. Moving the same `String` into a second closure is E0382, use of moved value. For data that should stay shared rather than copied, clone an `Rc` or `Arc` handle instead.
  • In Rust, if `let r = &theme;` and a `move` closure prints `r`, is the closure `'static`?
    No. `move` copies the reference `r` into the closure, so the closure still borrows `theme` and its type carries that borrow's lifetime. Passing it to a `'static` bound fails; the closure must own the `String`, for example by moving `theme` or a clone of it.
  • In Rust, does `move` change which `Fn` trait a closure implements?
    No. Which call traits a closure implements depends on what its body does with the captures, not on how they were captured, so a `move` closure that only reads its `String` can still be called repeatedly through a shared reference.

  • move makes the closure share the outer counter, so increments show up outside.
  • move only changes how non-Copy variables are captured.
  • A move closure can never borrow anything from the enclosing function.
  • Adding move always fixes E0373 with no other change.
  • move turns any closure into one that can be called only once.