Explanation
What just happened
thread::spawn got a move closure, so the new thread took ownership of names. main waited in join(). When the thread finished, names was dropped there, on the thread that owned it.
Try the what-if switch
- thread::scope: no
move. The scope waits for its threads before it returns, so the thread may just borrownames, and main keeps it.
Why the compiler refuses without move
A thread from thread::spawn can run after the function that started it returns, and that function’s locals are gone by then. A closure borrowing one could read freed memory, so thread::spawn only accepts closures that own their data ('static). That is error E0373.
When to use which
move: the thread needs the data and main doesn’t.thread::scope: borrow, read or even change locals for a short burst of parallel work.Arc: several threads share the data for a long time, like the shared counter withArc<Mutex<T>>.
Watch out
After move, using names in main is error E0382. Clone it first if both need it.
Common questions
What does closure may outlive the current function mean?
The closure you gave thread::spawn borrows a local variable, but the new thread can keep running after the function that spawned it has returned, when that variable is gone. So the compiler refuses, with error E0373.
How do I fix error E0373?
Add move, so the thread owns the values it uses. Or spawn inside thread::scope, which waits for its threads before returning, so they may borrow.
Why can't main use the variable after move?
It belongs to the thread now: using it in main fails with E0382, borrow of moved value. Clone it before the spawn, or share it with Arc if both need it.
Can a scoped thread change a borrowed value?
Yes. A thread in thread::scope can borrow mutably while main waits at the end of the scope, and main sees the change afterwards.
Verified: this timeline matches a real program, checked in CI on Rust 1.99 with Tokio 1.54. How we verify. Unclear or wrong? Tell us