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 settings = Rc::new(vec!["theme:dark", "lang:en"]);4let ui = Rc::clone(&settings);5let api = Rc::clone(&settings);67println!("UI: {:?}", *ui);8println!("API: {:?}", *api);9println!("Count: {}", Rc::strong_count(&settings)); // 3
Arc — safe, multi-threaded:
1use std::sync::Arc;2use std::thread;34let words = Arc::new(vec!["hello", "world", "rust"]);5let mut handles = vec![];67for i in 0..3 {8 let w = Arc::clone(&words);9 handles.push(thread::spawn(move || {10 println!("Thread {}: {:?}", i, *w);11 }));12}13for h in handles { h.join().unwrap(); }
When to use Rc:
When to use Arc:
Common mistakes: