0PricingLogin
Learn Rust Coding · Lesson

Moving Data into Threads

Use move closures correctly.

Closures Capture the Environment

A closure passed to thread::spawn can use variables from the surrounding scope. By default Rust borrows them.

But a spawned thread might outlive the function that created it, so a plain borrow is not safe. Rust rejects this at compile time.

The Borrow Problem

If a thread borrows a local variable, the compiler cannot prove the variable lives long enough. The thread could keep running after the variable is dropped.

The code below does not compile, because the closure only borrows data.

use std::thread;

fn main() {
    let data = vec![1, 2, 3];
    // ERROR: closure may outlive `data`
    let h = thread::spawn(|| {
        println!("{:?}", data);
    });
    h.join().unwrap();
}

All lessons in this course

  1. Spawning Threads
  2. Moving Data into Threads
  3. Sharing with Arc and Mutex
  4. Joining and Collecting Results
← Back to Learn Rust Coding