Use the `move` keyword with `thread::spawn` closures to transfer ownership of captured variables into the new thread.
To use a closure with thread::spawn that captures variables, add the move keyword to transfer ownership of those variables into the new thread.
use std::thread;
fn main() {
let list = vec![1, 2, 3];
thread::spawn(move || {
println!("From thread: {list:?}");
})
.join()
.unwrap();
}
The move keyword forces the closure to take ownership of list, ensuring the data lives long enough for the spawned thread to use it safely.
A closure is a small piece of code that can remember variables from where it was created. When you run this code on a separate thread, you must use the move keyword to physically copy or transfer those variables into the new thread's memory space. Think of it like handing a physical document to a colleague in another room; you must give them the actual paper, not just point to where it sits on your desk.