ArmaniazirustThreadspawinMoveCapture
{
The move closure is often used alongside thread::spawn because it allows you to use data from one thread in another thread.
}
{
we’re not using any data from the main thread in the spawned thread’s code. To use data from the main thread in the spawned thread, the spawned thread’s closure must capture the values it needs.
}
{
The move keyword overrides Rust’s conservative default of borrowing; it doesn’t let us violate the ownership rules.
}
{
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
}
When the spawned thread wants to access variables that are defined in the parent’s scope, called a capture, Rust often complains that captures must be moved into the closure. To indicate that you want to move ownership, anonymous functions take a move keyword:
use std::{thread, time};
thread::spawn(move || {
// ...
});
Why is move required? Closures spawned in subthreads can potentially outlive their calling scope.
As Rust will always ensure that accessing the data is valid,
it requires ownership to move to the closure itself. Here are some guidelines for using captures while you gain an understanding of how these work:
To reduce friction at compile time, implement Copy.
Values originating in outer scopes may need to have a static lifetime.
Spawned subthreads can outlive their parents. That implies that ownership should pass to the subthread with move.
ArmanRiazi