O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sharing the Copy types

Types that have the Copy type implemented can be trivially shared between threads, but, of course, the values get copied:

// sharing-immutables.rs use std::thread; use std::time; fn main() {     let mut num = 4;      for _ in 1..10 {         thread::spawn(move || {             num += 1;             println!("String is {}", num);         });     }     thread::sleep(time::Duration::from_secs(1));     println!("In main thread: num is now {}", num); } 

The output shows us that the numbers in the threads are separate copies:

Nevertheless, if immutable values are all you need between your threads, and runtime space efficiency is not a concern, this is fine. The Copy types ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required