Move closures across threads
Quick answer
A move closure captures used values by value. It is often the right way to give a spawned thread ownership of its input.
Transfer or share deliberately
The move keyword changes capture mode; it does not automatically clone values or turn a borrowed reference into owned data. A non-Copy captured String moves into the closure, whereas a Copy integer can remain usable by the parent. Use Arc cloning if both sides need ownership of immutable data.
fn main() { let name = String::from("Rust"); let worker = std::thread::spawn(move || name.len()); println!("{}", worker.join().unwrap());}Expected stdout (not executed):
4The String lives with the worker until it is no longer needed.
use std::sync::Arc;fn main() { let label = Arc::new(String::from("report")); let copy = Arc::clone(&label); let worker = std::thread::spawn(move || copy.len()); println!("{} {}", label.as_str(), worker.join().unwrap());}Expected stdout (not executed):
report 6Cloning the Arc adds a shared owner, not a duplicate String.
Common mistake
Moving a reference does not extend the lifetime of its referent.
Try it yourself
Try using name after spawn in the first example, then explain the rejection.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Move closures across threads — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A move closure captures a u32 local and sends it to a thread. Can the parent still use its value?
Move closures across threads — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let name = String::from("Rust"); let worker = std::thread::spawn(move || name.len()); println!("{}", worker.join().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Move closures across threads — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::sync::Arc; fn main() { let label = Arc::new(String::from("report")); let copy = Arc::clone(&label); let worker = std::thread::spawn(move || copy.len()); println!("{} {}", label.as_str(), worker.join().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.