std-function

thread::scope: borrow local data safely

A scoped worker can borrow data that outlives the scope. Workers not explicitly joined are joined before scope returns; thread-local destructor completion has separate platform limitations. Expected stdout (not executed): 15 3 Common mistake: Moving all data just to satisfy an unscoped spawn when a scoped borrow is sufficient.

Formal Syntax & Structure

rust syntaxrust
thread::scope(|s| { s.spawn(|| ...); })

Working Example

Example Snippetrust
fn main() {    let numbers = vec![3, 5, 7];    let sum = std::thread::scope(|s| s.spawn(|| numbers.iter().sum::<i32>()).join().unwrap());    println!("{} {}", sum, numbers.len());}
Rust Reference