When would you use Rc, Arc, RefCell or Mutex?
Ownership allows one owner, but graphs and shared state need more. Rust pushes the choice into types.
Rc<T>: single-threaded reference counting.cloneincrements a count and creates another owner; not atomic.Arc<T>: atomic reference counting, safe to share across threads.RefCell<T>: runtime-checked interior mutability for one thread. Borrowing rules are enforced at runtime and violations panic.Mutex<T>andRwLock<T>: cross-thread interior mutability. Locking returns a guard and poisoning is tracked.
use std::rc::Rc;
use std::cell::RefCell;
let shared = Rc::new(RefCell::new(vec![1]));
let alias = Rc::clone(&shared);
alias.borrow_mut().push(2);
Combine Rc<RefCell<T>> for single-threaded shared mutation and Arc<Mutex<T>> across threads. Rc and RefCell are not Send, so the compiler prevents using them across threads. Use Rc::downgrade to create a Weak reference that breaks reference cycles which would otherwise leak.