12.5 Closures and Concurrency
Rust encourages concurrency through safe abstractions. Closures are integral to this approach because you often want to run a piece of code in a new thread or async task while capturing local variables.
12.5.1 Executing Closures in Threads
The move
keyword ensures data
is owned by the thread, preventing it from being dropped prematurely.
12.5.2 Why move
Is Required
Threads may outlive the scope in which they are spawned. If the closure captured variables by reference (rather than by ownership), you could end up with dangling references:
12.5.3 Lifetimes of Closures
Closures that outlive their immediate scope need to ensure they either:
- Own the data they capture (via
move
), or - Refer only to
'static
data (e.g., string literals).