Rc (Reference Counted) provides multiple ownership through non-atomic reference counting and is NOT thread-safe. Arc (Atomic Reference Counted) provides multiple ownership through atomic reference counting and IS thread-safe.
Rc — single-threaded:
1use std::rc::Rc;23let data = Rc::new(String::from("hello"));4let data2 = Rc::clone(&data);5println!("Count: {}", Rc::strong_count(&data)); // 26// Will NOT compile if sent to another thread
Arc — multi-threaded:
1use std::sync::Arc;2use std::thread;34let data = Arc::new(vec![1, 2, 3]);56for i in 0..3 {7 let data_clone = Arc::clone(&data);8 thread::spawn(move || {9 println!("Thread {}: {:?}", i, data_clone);10 });11}12// All threads can safely read the same data
When to use Rc:
When to use Arc:
Common mistakes: