Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let name = String::from("Ana");
let greet = move || println!("hi {name}");

Try it

Rust Capture by reference versus by value

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.

Rust Threads and returned closures

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

Rust
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

  • move is about capture, not about the closure traits. A move closure can still implement Fn or FnMut; whether it is FnOnce depends only on what the body does with the captured values.
  • Copy types are copied, so a move closure that mutates a copied integer changes only its own copy, as the first example shows.
  • References are moved too. A move closure that uses &data captures the reference, not data. To share ownership between threads, clone an Arc first 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 'static closures, so borrowed locals cannot be captured; move is almost always required for thread::spawn. Scoped threads (thread::scope) are the exception because they may borrow.
  • Edition 2021 closures capture disjoint fields, so move moves only the used fields of a struct, not the whole struct.
  • Pattern: a move closure returned as impl Fn or Box<dyn Fn> is how Rust builds function factories.