- Arc
- clone
Pass reference of read-only vector to thread
- Arc allows us to have reference counting.
- Here the clone only copies the reference and not the whole data structure.
examples/threads/pass-reference-to-vector/src/main.rs
use std::sync::Arc; fn main() { let animals = Arc::new(Vec::from_iter(["mouse", "elephant", "cat", "dog", "giraffe"].map(|animal| animal.to_string()))); println!("{:?}", animals); { let animals = animals.clone(); let handle = std::thread::spawn(move || { list_animals(&animals); }); handle.join().unwrap(); } println!("{:?}", animals); } fn list_animals(animals: &Vec<String>) { for animal in animals { println!("{}", animal); } }