RRust By Example
intermediateConcurrency

Thread with Move

Transfer ownership to threads with move closures.

Thread with Move

Transfer ownership to threads with move closures.

Difficulty

Intermediate

Code

rust
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.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Concurrency Examples