Rc = reference counted, single-threaded, non-atomic. Arc = atomic reference counted, multi-threaded, atomic. Same shared-ownership concept, different thread-safety.
Rc — fast, single-thread:
1use std::rc::Rc;23let shared = Rc::new(String::from("hello"));4let a = Rc::clone(&shared);5let b = Rc::clone(&shared);67println!("{} {} {}", *shared, *a, *b);8println!("Count: {}", Rc::strong_count(&shared)); // 3
Arc — safe, multi-threaded:
1use std::sync::Arc;2use std::thread;34let data = Arc::new(vec![1, 2, 3, 4, 5]);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: