Both Rc and Arc provide shared ownership through reference counting, but Rc uses non-atomic operations (single-thread only, faster) while Arc uses atomic operations (thread-safe, slightly slower).
Rc — non-atomic reference counting:
1use std::rc::Rc;23let data = Rc::new(vec![1, 2, 3]);4let shared = Rc::clone(&data);5println!("Refs: {}", Rc::strong_count(&data)); // 267// This won't compile:8// std::thread::spawn(move || println!("{:?}", shared));
Arc — atomic reference counting:
1use std::sync::Arc;2use std::thread;34let data = Arc::new(vec![1, 2, 3]);5let mut handles = vec![];67for i in 0..3 {8 let data = Arc::clone(&data);9 handles.push(thread::spawn(move || {10 println!("Thread {}: {:?}", i, *data);11 }));12}1314for h in handles {15 h.join().unwrap();16}
When to use Rc:
When to use Arc:
Common mistakes: