W3cubDocs

/Rust

Keyword move

Capture a closure's environment by value.

move converts any variables captured by reference or mutable reference to owned by value variables.

let capture = "hello";
let closure = move || {
    println!("rust says {}", capture);
};

Note: move closures may still implement Fn or FnMut, even though they capture variables by move. This is because the traits implemented by a closure type are determined by what the closure does with captured values, not how it captures them:

fn create_fn() -> impl Fn() {
    let text = "Fn".to_owned();

    move || println!("This is a: {}", text)
}

    let fn_plain = create_fn();

    fn_plain();

move is often used when threads are involved.

let x = 5;

std::thread::spawn(move || {
    println!("captured {} by value", x)
}).join().unwrap();

// x is no longer available

move is also valid before an async block.

let capture = "hello";
let block = async move {
    println!("rust says {} from async block", capture);
};

For more information on the move keyword, see the closure's section of the Rust book or the threads section

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/keyword.move.html