Shared Ownership with Rc and RefCell
Persistent lists, interior mutability, and where reference cycles leak.
use std::rc::Rc;
pub struct List<T> {
head: Option<Rc<Node<T>>>,
}
Rc<T> is reference counting: cloning is cheap and the value drops when the last handle
goes. That gives you a persistent list — two lists can share a tail.
The price: Rc only hands out shared references, so you can’t mutate through it. That’s what
RefCell<T> is for — it moves the borrow check from compile time to runtime, panicking if
you violate the rules.
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
Where this bites: Rc cycles never drop. A doubly-linked list where both directions are
Rc leaks every node. The fix is Weak<T> for the back-pointers — it doesn’t contribute to
the count and upgrades to Option<Rc<T>> when you need it.
If you want the full treatment, Learn Rust With Entirely Too Many Linked Lists is the canonical deep dive.