Rc and Arc both provide shared ownership through reference counting, but Rc is single-threaded (uses non-atomic operations) while Arc is multi-threaded (uses atomic operations for thread safety).
Rc — single-threaded reference counting:
1use std::rc::Rc;23let data = Rc::new(vec![1, 2, 3]);4let clone1 = Rc::clone(&data);5let clone2 = Rc::clone(&data);6println!("Strong count: {}", Rc::strong_count(&data)); // 37// This would NOT compile:8// std::thread::spawn(move || println!("{:?}", data));
Arc — atomic reference counting:
1use std::sync::Arc;2use std::thread;34let data = Arc::new(vec![1, 2, 3]);56let handles: Vec<_> = (0..4).map(|i| {7 let data = Arc::clone(&data);8 thread::spawn(move || {9 println!("Thread {}: {:?}", i, *data);10 })11}).collect();1213for h in handles {14 h.join().unwrap();15}
Performance comparison:
When to use Rc:
When to use Arc:
Common mistakes:
Rc<i32> cannot be sent between threads safely).