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
movetransfers the captured values into the closure.- Without it the borrow checker refuses the spawn.
- Each thread gets its own copy or its own value.
Keywords and builtins used here
Vecfnforinletmainmovemutuse
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.
Step 2 of 3 in Threads, step 2 of 15 in Concurrency & async.