Rc and Arc both enable shared ownership via reference counting, but Rc is non-atomic (single-thread, faster) while Arc is atomic (multi-thread, thread-safe).
Rc — non-atomic, single-thread:
1use std::rc::Rc;23let data = Rc::new(String::from("shared data"));4let ref1 = Rc::clone(&data);5let ref2 = Rc::clone(&data);67println!("Strong: {}, Weak: {}",8 Rc::strong_count(&data),9 Rc::weak_count(&data)); // 3, 0
Arc — atomic, multi-thread:
1use std::sync::Arc;2use std::thread;34let config = Arc::new(vec![1, 2, 3, 4, 5]);5let mut threads = vec![];67for i in 0..4 {8 let cfg = Arc::clone(&config);9 threads.push(thread::spawn(move || {10 let sum: i32 = cfg.iter().sum();11 println!("Thread {}: sum = {}", i, sum);12 }));13}1415for t in threads {16 t.join().unwrap();17}
When to use Rc:
When to use Arc:
Common mistakes: