Thread with Move
Transfer ownership to threads with move closures.
Thread with Move
Transfer ownership to threads with move closures.
Difficulty
Intermediate
Code
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("data in thread: {:?}", data);
let sum: i32 = data.iter().sum();
sum
});
let result = handle.join().unwrap();
println!("sum: {}", result);
}Explanation
move transfers ownership to thread closures.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the concurrency category to build a complete understanding of this topic.