Rust Reference ยท Keywords and Statements
The move keyword
Reference for Rust move closures: how closures capture variables, forcing capture by value, threads and 'static, Copy types, async move and returning closures.
A closure normally captures each variable in the least demanding way its body allows: by shared reference, by mutable reference, or by value only if the body consumes it. The move keyword changes this: every variable the closure mentions is captured by value, meaning moved (or copied, for Copy types) into the closure.
Use move when the closure must outlive the scope that created it, which is the case for threads, returned closures and spawned tasks.
let name = String::from("Ana"); let greet = move || println!("hi {name}");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
move |args| body move || { ... } async move { ... }
| Form | Effect |
|---|---|
move || ... |
All used variables are captured by value. |
async move { ... } |
The async block owns its captured variables instead of borrowing them. |
Usage notes
moveis about capture, not about the closure traits. Amoveclosure can still implementFnorFnMut; whether it isFnOncedepends only on what the body does with the captured values.- Copy types are copied, so a
moveclosure that mutates a copied integer changes only its own copy, as the first example shows. - References are moved too. A
moveclosure that uses&datacaptures the reference, notdata. To share ownership between threads, clone anArcfirst and move the clone. - Cloning before moving. To keep using a value, make a clone in a separate binding:
let name2 = name.clone(); move || name2.len(). - Threads and tasks require
'staticclosures, so borrowed locals cannot be captured;moveis almost always required forthread::spawn. Scoped threads (thread::scope) are the exception because they may borrow. - Edition 2021 closures capture disjoint fields, so
movemoves only the used fields of a struct, not the whole struct. - Pattern: a
moveclosure returned asimpl FnorBox<dyn Fn>is how Rust builds function factories.