Share locally, check carefully.
Separate shared ownership from runtime-checked mutation.
01 Understand the contract
Rc<T> provides reference-counted shared ownership within one thread. RefCell<T> allows interior mutation by checking borrowing rules at runtime: many shared borrows or one exclusive borrow. Violations panic with borrow or can return an error with try_borrow. Rc does not make data thread-safe, and reference cycles can prevent cleanup; Weak references help represent non-owning back-links. Prefer simple ownership first, then introduce these tools when the graph of owners genuinely requires them.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
use std::{cell::RefCell, rc::Rc};
fn main() {
let shared = Rc::new(RefCell::new(vec!["plan"]));
let other = Rc::clone(&shared);
other.borrow_mut().push("build");
println!("{:?}", shared.borrow());
println!("owners={}", Rc::strong_count(&shared));
}["plan", "build"] owners=2
- 1
Rc::clone shares the allocation rather than copying the vector.
- 2
The temporary mutable borrow ends after push.
- 3
The later shared borrow sees the update.
cargo run -p lesson_rc_refcell03 Mind the boundary
04 Your next build
Hold a shared borrow and confirm try_borrow_mut fails, then succeeds after the shared guard is dropped.
Reveal one possible solution +
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(1);
let guard = cell.borrow();
assert!(cell.try_borrow_mut().is_err());
drop(guard);
*cell.try_borrow_mut().unwrap() = 2;
assert_eq!(*cell.borrow(), 2);
}05 Check your reasoning
Can Rc by itself be sent safely between threads?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.