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

This example demonstrates how to use thread with move in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

More Concurrency Examples