How to Use Closures with Thread

:spawn in Rust

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.