Rc = reference counted, single-threaded, uses non-atomic operations. Arc = atomic reference counted, multi-threaded, uses atomic operations. Same API, different thread-safety guarantees.
Rc — fast, single-thread:
1use std::rc::Rc;23let config = Rc::new(vec!["debug", "verbose"]);4let reader1 = Rc::clone(&config);5let reader2 = Rc::clone(&config);67// All in the same thread8println!("{}", reader1.len()); // 29println!("{}", reader2.len()); // 2
Arc — safe, multi-thread:
1use std::sync::Arc;2use std::thread;34let data = Arc::new(vec![1, 2, 3, 4, 5]);5let mut handles = vec![];67for chunk_size in [1, 2, 5] {8 let d = Arc::clone(&data);9 handles.push(thread::spawn(move || {10 println!("Chunk {}: {:?}", chunk_size,11 d.chunks(chunk_size).collect::<Vec<_>>());12 }));13}1415for h in handles {16 h.join().unwrap();17}
When to use Rc:
When to use Arc:
Common mistakes: