
Understand it
Rc<T> keeps a count and frees when it reaches zero, but only hands out shared references. Pairing it with RefCell<T> lets you mutate through that shared handle, with the borrow rules checked at runtime instead — a violation panics rather than failing to compile. Neither is thread-safe; that is Arc and Mutex.
Rc<T> provides shared ownership within one thread. Each clone of an Rc is another strong handle to the same allocation, not a deep copy of T. The allocation is released when its last strong owner disappears. Because multiple owners can access the same value, Rc<T> normally provides shared read access. Wrapping the value in RefCell<T> permits mutation by checking the borrow rule at runtime.
In the sample, both shared and second refer to the same cell. A borrow_mut() guard grants exclusive access while it is alive; a borrow() guard permits reading, possibly alongside other readers. If a writer and reader overlap, RefCell panics, or try_borrow returns an error. Keep the guard's lifetime short. If the mutation is awkward only because the ownership design is unclear, a simpler owner with explicit mutable borrowing may be preferable.
Use Rc<RefCell<T>> for a local graph or UI state where several single-threaded owners truly need to share a mutable value. It is not a concurrency primitive. Rc does not implement the thread-safety traits needed for cross-thread sharing, and RefCell does not synchronize threads. The rough cross-thread counterparts are Arc<T> for shared ownership and a Mutex<T> or another synchronization strategy for mutation. Draw each owner and each active borrow separately; counting handles and checking access are two different mechanisms.
If you need only several read-only owners, Rc<T> alone is simpler. Add RefCell only when mutation behind shared ownership is a real requirement.
Read the code
use std::cell::RefCell;
use std::rc::Rc;
let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
let second = Rc::clone(&shared);
second.borrow_mut().push(4);
println!("{:?}", shared.borrow());
println!("owners {}", Rc::strong_count(&shared));Shared ownership on the outside, controlled mutation on the inside.
Practice starter
use std::cell::RefCell;
let cell = RefCell::new(5);
let a = cell.borrow_mut();
let b = cell.borrow_mut();Try it
Share one vector between two handles and mutate it through both.
What success looks like: Both handles observe the change and the count is correct.
Check your understanding
What happens on the second borrow_mut?
Reveal the answer
- It compiles and works
- It panics at runtime
- It is a compile error
RefCell enforces the same rule, just later and with a panic.
Go deeper
Common misconception: “The compiler rejects a second borrow_mut, as it does for &mut.”
RefCell moves the borrow rules to runtime; breaking them panics. The second borrow_mut compiles, then panics because the first guard is still alive.
- Share the allocation:
Rc::clone(&shared)createssecond, another handle to the oneRefCell. The vector is not copied. - Mutate through a handle:
second.borrow_mut()returns a guard for that statement, andpush(4)adds to the vector both handles share. - Read both facts:
shared.borrow()now shows[1, 2, 3, 4]andRc::strong_countreports 2: counting owners and checking access are separate jobs.
Transfer challenge: Hold let guard = shared.borrow(); across the push and predict what happens. Then call try_borrow_mut at that spot and read the Err it returns.
Connections
- Box<T>: Heap allocation and recursive types
- Deref & Drop: Making a type behave like a reference
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Rc & RefCell (courseId "projects", lessonId "rc-refcell") Link: https://crabrix.com/learn/projects/rc-refcell/ Goal: RefCell moves the borrow rules to runtime; breaking them panics. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=projects/rc-refcell) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.