Rc = reference counted, NOT thread-safe, non-atomic. Arc = atomic reference counted, thread-safe, atomic. Same shared-ownership concept, different thread-safety.
Rc — fast, single-thread:
1use std::rc::Rc;23let shared = Rc::new(vec![1, 2, 3]);4let a = Rc::clone(&shared);5let b = Rc::clone(&shared);67println!("Count: {}", Rc::strong_count(&shared)); // 38println!("Values: {:?} {:?} {:?}", *shared, *a, *b);
Arc — safe, multi-threaded:
1use std::sync::Arc;2use std::thread;34let data = Arc::new(vec!["a", "b", "c"]);5let mut handles = vec![];67for i in 0..3 {8 let d = Arc::clone(&data);9 handles.push(thread::spawn(move || {10 println!("Thread {}: {:?}", i, *d);11 }));12}13for h in handles { h.join().unwrap(); }
When to use Rc:
When to use Arc:
Common mistakes: