[−][src]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); };Run
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();Run
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 availableRun
move
is also valid before an async block.
let capture = "hello"; let block = async move { println!("rust says {} from async block", capture); };Run
For more information on the move
keyword, see the closure's section
of the Rust book or the threads section