std-method

Builder::spawn_scoped: configured borrowing worker

Combine scoped borrowing with a configured builder and a fallible launch. The borrowed data must remain valid for the scope. Expected stdout (not executed): 14 Common mistake: Using ordinary Builder::spawn for a short-lived borrow.

Formal Syntax & Structure

rust syntaxrust
builder.spawn_scoped(scope, F) -> io::Result<ScopedJoinHandle<T>>

Working Example

Example Snippetrust
fn main() {    let data = [2, 4, 8];    let result = std::thread::scope(|s| std::thread::Builder::new().name("sum".into()).spawn_scoped(s, || data.iter().sum::<i32>()).unwrap().join().unwrap());    println!("{result}");}
Rust Reference