Sub topic 3
Rc<RefCell<T>>: Shared, Mutable Data
Assume you know Rust ownership, borrowing, Rc<T>, and basic generics. This chapter combines those ideas for single-threaded shared state.
Combining `Rc` and `RefCell`
Rc<T> gives several owners of the same value. RefCell<T> allows mutation through a shared reference by checking borrowing rules at runtime. Together, Rc<RefCell<T>> lets multiple parts of a program share and modify data.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
let other = Rc::clone(&shared);
other.borrow_mut().push(4);
println!("{:?}", shared.borrow());
}The output is [1, 2, 3, 4]. A second mutable borrow while the first is active causes a runtime panic. Use short borrow scopes, or try_borrow and try_borrow_mut when failure should be handled.
`Cell<T>` for `Copy` Values
Cell<T> is another interior-mutability type. It works best when T implements Copy, such as integers and booleans. It moves values in and out instead of returning references.
use std::cell::Cell;
fn main() {
let counter = Cell::new(0);
counter.set(counter.get() + 1);
println!("{}", counter.get());
}Use RefCell for borrowing larger values. Use Cell for simple replaceable values.
Reference Cycles and `Weak<T>`
An ownership cycle occurs when values own one another through Rc. Their strong counts never reach zero, so Rust cannot drop them. This leaks memory.
Weak<T> does not keep a value alive. Call upgrade() to get Option<Rc<T>>. It returns None after the target has been dropped.
Crossing Threads: `Arc` and `Mutex`
Rc and RefCell are not thread-safe. For shared data across threads, use Arc<T>, an atomically reference-counted pointer, and usually Mutex<T> for synchronized mutation. A mutex allows only one thread to access its protected data at a time.
Choosing a Pointer
| Need | Typical choice |
|---|---|
| Heap allocation or recursive type | `Box<T>` |
| Shared ownership in one thread | `Rc<T>` |
| Runtime-checked mutation | `RefCell<T>` |
| Shared mutable data in one thread | `Rc<RefCell<T>>` |
| Shared mutable data across threads | `Arc<Mutex<T>>` |
Exercise
Why can Rc<RefCell<T>> mutate shared data, and why is it unsuitable for multiple threads?
Show answer
RefCell<T> checks borrowing at runtime, while Rc<T> supplies shared ownership. Neither type provides the synchronization and thread-safety guarantees required across threads.