typestar

move closures in Rust

A thread outlives the caller's stack frame, so it must own what it captures.

use std::thread;

fn main() {
    let words = vec!["ada".to_string(), "grace".to_string()];
    let mut handles = Vec::new();

    for word in words {
        handles.push(thread::spawn(move || {
            format!("{} has {} letters", word, word.len())
        }));
    }

    for handle in handles {
        println!("{}", handle.join().unwrap());
    }
}

How it works

  1. move transfers the captured values into the closure.
  2. Without it the borrow checker refuses the spawn.
  3. Each thread gets its own copy or its own value.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
298
Tokens
102
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 2 of 3 in Threads, step 2 of 15 in Concurrency & async.

← Previous Next →