The Analogy: The Key Tally At The Shared Workshop
Six teams use one workshop and each of them has a key. The caretaker keeps a tally on a board beside the door: not who has keys, just how many are out. He has never needed to know whose they are.
No single team owns the workshop and no single team decides when it closes. A team that finishes hands its key back and the tally drops by one, and when the tally reaches zero the caretaker locks up, cuts the power, and the workshop is gone. Cutting an extra key is a two-second job that creates no second workshop, and that is the entire appeal of the arrangement: six teams, one workshop, six cheap keys.
What a key does not give you is the right to rearrange the place. Five other teams are relying on the bench being where the bench was, and not one of them is obliged to ask your permission or even to tell you they are in the building. A key gets you in and lets you use what is there. It does not make you the person who decides where things go.
Two ways this arrangement goes wrong, both worth knowing before you meet them. If team A's key is locked inside team B's toolbox and team B's key is locked inside team A's, neither key ever comes back, the tally never reaches zero, and the caretaker keeps paying to heat a workshop nobody is in. And for the inspector who only needs to look in occasionally there is a different pass altogether: it gets him through the door if the workshop is still open, it tells him plainly when it is not, and it is never counted on the board.
Syntax or Core Structure
Rc stands for reference counted. Rc::new takes ownership of a value, and every clone is another handle on the same one:
use std::rc::Rc;
fn main() {
let plan = Rc::new(String::from("site-plan-A0"));
println!("count {}", Rc::strong_count(&plan));
let survey = Rc::clone(&plan);
println!("count {}", Rc::strong_count(&plan));
{
let costing = Rc::clone(&plan);
println!("count {}", Rc::strong_count(&plan));
println!("costing sees {costing}");
}
println!("count {}", Rc::strong_count(&plan));
println!("len {} same text {}", plan.len(), *survey == *plan);
println!("same allocation {}", Rc::ptr_eq(&plan, &survey));
}
Output:
count 1
count 2
count 3
costing sees site-plan-A0
count 2
len 12 same text true
same allocation true
The count went to three and came back to two without anybody writing the decrement, because costing went out of scope at the closing brace and dropping an Rc is what hands the key back.
Two conventions in that code are worth adopting deliberately. Rc::clone(&plan) and plan.clone() do exactly the same thing, and the community writes the first one because it looks like what it is -- a counter increment -- where .clone() on a Rc<String> reads like a copy of the string and is not one. And Rc::ptr_eq asks "the same allocation?", which is a different question from == asking "the same value?"; here both are true, and in a program with two identical strings only one of them would be.
Box<T> | Rc<T> | |
|---|---|---|
| Owners at any one time | Exactly one | Any number |
| What cloning does | Deep-copies T, and needs T: Clone | Bumps a counter, copies no data at all |
| The value is freed when | The single owner is dropped | The last handle is dropped |
| What you can get out of it | &T and &mut T | &T only |
Moving the value out with * | Allowed | Not allowed |
| Across threads | Fine if T allows it | Single-threaded only |
Technical Depth: The Tally, The Locked Bench, And The Two Toolboxes
Nothing happens until the count reaches zero
use std::rc::Rc;
struct Drawing {
id: &'static str,
}
impl Drop for Drawing {
fn drop(&mut self) {
println!("scrapped {}", self.id);
}
}
fn main() {
let a = Rc::new(Drawing { id: "A0-101" });
println!("count {}", Rc::strong_count(&a));
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("count {}", Rc::strong_count(&a));
drop(b);
println!("after b {}", Rc::strong_count(&a));
drop(c);
println!("after c {}", Rc::strong_count(&a));
println!("main ending");
}
Output:
count 1
count 3
after b 2
after c 1
main ending
scrapped A0-101
Dropping b printed nothing. Dropping c printed nothing. Drawing::drop ran exactly once, after the last line of main, when a itself went out of scope and took the count to zero. That is the guarantee Rc offers and the only one: the value is destroyed once, when the last handle goes, and no earlier.
The bench stays where it is
use std::rc::Rc;
fn main() {
let mut solo = Rc::new(String::from("draft"));
if let Some(s) = Rc::get_mut(&mut solo) {
s.push_str("-v2");
}
println!("{solo}");
let shared = Rc::clone(&solo);
match Rc::get_mut(&mut solo) {
Some(s) => s.push_str("-v3"),
None => println!("shared, cannot edit in place"),
}
println!("{solo} {shared}");
}
Output:
draft-v2
shared, cannot edit in place
draft-v2 draft-v2
Rc<T> derefs to &T and stops there. There is no &mut to be had while anybody else might be holding a handle, because a second holder would then be watching a value change under it with no way to know. Rc::get_mut is the narrow exception: it hands you a &mut T only when the strong count is one and no weak handles exist, which is to say only when you are demonstrably alone -- and it returns Option rather than panicking so that you have to say what happens otherwise.
Rc::make_mut takes the other road. If the value is shared it clones it first and hands you a &mut to your own private copy, quietly detaching you from everybody else. That is exactly right for copy-on-write and exactly wrong if you expected your edit to be seen by the other holders. When shared mutation is what you need, the tool is Rc<RefCell<T>>, and RefCell is the next lesson.
Two toolboxes, and the pass that is not counted
use std::rc::{Rc, Weak};
struct Node {
id: &'static str,
parent: Option<Weak<Node>>,
}
fn main() {
let root = Rc::new(Node { id: "root", parent: None });
let child = Rc::new(Node { id: "child", parent: Some(Rc::downgrade(&root)) });
println!("root strong {} weak {}", Rc::strong_count(&root), Rc::weak_count(&root));
match &child.parent {
Some(w) => match w.upgrade() {
Some(p) => println!("{} parent is {}", child.id, p.id),
None => println!("{} parent is gone", child.id),
},
None => println!("{} has no parent", child.id),
}
let inspector = Rc::downgrade(&root);
drop(root);
println!("upgrade after drop {}", inspector.upgrade().is_some());
}
Output:
root strong 1 weak 1
child parent is root
upgrade after drop false
Make parent an Option<Rc<Node>> instead, give the root a Vec<Rc<Node>> of children, and you have built the two locked toolboxes: the child keeps the parent's count above zero, the parent keeps the child's count above zero, neither ever reaches zero, and the memory is never freed and the destructors never run. Rust's ownership rules do not prevent this. It is a leak, not a use-after-free -- safe, and still a bug.
Weak<T> is the back-edge that breaks it. Rc::downgrade produces one, it is counted separately and keeps nothing alive, and the only way to read through it is upgrade(), which returns Option<Rc<T>> and answers None once the value is gone. The final line proves it: the inspector's pass got him nothing after the workshop closed, and asking was safe.
Rc<T> | Weak<T> | |
|---|---|---|
Shows up in strong_count | Yes | No, in weak_count instead |
| Keeps the value alive | Yes | No |
| Reading the value | Directly, and always valid | Through upgrade(), which may answer None |
| The right choice for | The owning direction | Back-edges, observers, caches |
One more limit, which the last three lessons of this module exist to address: Rc is not Send and not Sync, because the count is incremented without atomics. Hand one to thread::spawn and the compiler stops you, naming Send as the missing trait. Arc<T> is the same interface with atomic counting, and it costs slightly more per clone, which is why Rc still exists.
Real World Example: One Rate Card, Four Bookings, And Receipts That Do Not Hold On
Two rate cards exist and four bookings need them. Copying a card into every booking would be wasteful and would mean four places to correct; borrowing one would tie every booking's lifetime to the function that built it. So the cards are shared, and the receipts that refer back to the bookings deliberately do not keep them alive:
use std::rc::{Rc, Weak};
struct Rates {
name: &'static str,
per_minute: u32,
minimum: u32,
}
struct Booking {
id: &'static str,
minutes: u32,
rates: Rc<Rates>,
}
impl Booking {
fn pence(&self) -> u32 {
let raw = self.minutes * self.rates.per_minute;
if raw < self.rates.minimum {
self.rates.minimum
} else {
raw
}
}
}
struct Day {
date: &'static str,
bookings: Vec<Rc<Booking>>,
}
struct Receipt {
booking: Weak<Booking>,
}
fn main() {
let standard = Rc::new(Rates {
name: "standard",
per_minute: 6,
minimum: 300,
});
let weekend = Rc::new(Rates {
name: "weekend",
per_minute: 4,
minimum: 200,
});
let day = Day {
date: "2026-03-14",
bookings: vec![
Rc::new(Booking { id: "b-01", minutes: 20, rates: Rc::clone(&standard) }),
Rc::new(Booking { id: "b-02", minutes: 90, rates: Rc::clone(&standard) }),
Rc::new(Booking { id: "b-03", minutes: 30, rates: Rc::clone(&weekend) }),
Rc::new(Booking { id: "b-04", minutes: 15, rates: Rc::clone(&standard) }),
],
};
println!("{} {} bookings", day.date, day.bookings.len());
let mut total = 0;
for b in &day.bookings {
println!(" {} {:3} min {:5} {}", b.id, b.minutes, b.pence(), b.rates.name);
total += b.pence();
}
println!("total {total}");
println!("standard held by {}", Rc::strong_count(&standard));
println!("weekend held by {}", Rc::strong_count(&weekend));
let receipts: Vec<Receipt> = day
.bookings
.iter()
.map(|b| Receipt { booking: Rc::downgrade(b) })
.collect();
println!("receipts {} weak on b-01 {}", receipts.len(), Rc::weak_count(&day.bookings[0]));
match receipts[1].booking.upgrade() {
Some(b) => println!("receipt 1 -> {} at {}", b.id, b.pence()),
None => println!("receipt 1 -> booking gone"),
}
drop(day);
let live = receipts
.iter()
.filter(|r| r.booking.upgrade().is_some())
.count();
println!("after the day closes, live receipts {live}");
}
Output:
2026-03-14 4 bookings
b-01 20 min 300 standard
b-02 90 min 540 standard
b-03 30 min 200 weekend
b-04 15 min 300 standard
total 1340
standard held by 4
weekend held by 2
receipts 4 weak on b-01 1
receipt 1 -> b-02 at 540
after the day closes, live receipts 0
standard held by 4 is the tally on the board: the original binding plus the three bookings that reference it. Nothing in the program decided in advance how many bookings would use a card, no booking knows how many others share its card, and correcting the minimum charge is a change in one place that every holder sees immediately. Three of the four amounts are the minimum rather than the per-minute total, which is the sort of thing that goes wrong quietly when a rate card has been copied four times and only three copies get updated.
The obvious question is why not &Rates. Here a plain reference would work, and it would be the better choice, because everything lives in one function and the borrow checker can see that standard outlives the bookings. It stops working the moment a Booking has to be returned from the function that built it, stored in a struct with an unrelated lifetime, or dropped into a collection that outlives its creator. Rc is the answer to a specific problem: these values share, and I cannot prove to the compiler in advance which of them dies last.
The receipts are the other half of the lesson. A receipt refers to a booking but must not keep it alive -- closing the day's records should genuinely close them -- so it holds a Weak. upgrade() is the moment of truth, and it returns Option precisely so that the answer after drop(day) can be an honest None for all four. Had Receipt held an Rc<Booking> instead, drop(day) would have freed nothing at all, the four bookings would still be sitting in memory, and the only symptom would be a program that slowly grows. That is the two locked toolboxes, in code that looks entirely reasonable.
The limits are worth being blunt about. Nothing here can be changed: correcting b-02's minutes means building a new Booking, because Rc hands out & and nothing more, and Rc<RefCell<T>> in the next lesson is what buys shared mutation. All of it is single-threaded -- move a Booking to another thread and the compiler refuses on Send, with Arc as the swap. Every Rc::clone is a real increment, cheap but not free, so cloning inside a hot loop for no reason is still waste. And strong_count is a snapshot rather than a promise: it is genuinely useful in a test or a diagnostic print, and code that makes decisions based on it is usually code that has lost track of its own ownership.
Common Mistakes
- Writing
plan.clone()on anRc. It compiles and does the right thing, but every reader has to work out whether a wholeStringwas just copied.Rc::clone(&plan)says "count increment" at a glance, and the two are identical in behaviour.
- Expecting a
&mutout of anRc. There is none, by design.Rc::get_mutworks only when you are provably the sole holder, and reaching for it repeatedly is a sign that the value wantedRefCellinside it from the start.
- Building a cycle out of two strong handles. A parent holding children and children holding parents, both as
Rc, leaks the whole graph. Nothing warns you, no test fails, and the destructors simply never run.
- Using
Rcwhere a reference would do. Inside one function, over one clear scope,&Tis cheaper, simpler and checked.Rcearns its keep only when the lifetimes genuinely cannot be written down.
- Sending an
Rcto another thread. The count is not atomic, soRcis neitherSendnorSync, and the compiler says so by name.Arc<T>is the drop-in with atomic counting.
- Unwrapping
upgrade(). The whole point ofWeakis that the value may be gone.upgrade().unwrap()converts a designed-for case into a panic, usually on the one input that mattered.
- Branching on
strong_count. It is a snapshot, and by the time you have matched on it another handle may have been created or dropped. Use it in tests and diagnostics, not in logic.
- Assuming
Rc::make_mutedits the shared value. When the value is shared it clones first, so your edit lands on a private copy and the other holders see nothing change. That is copy-on-write, and it is only sometimes what you wanted.
- Reaching for
Rc<Vec<T>>and then trying to push. The whole vector is immutable through every handle.Rc<RefCell<Vec<T>>>is the shape that allows it, with the costs the next lesson describes.
Best Practices
- Write
Rc::clone(&x), always, so that a cheap count bump never reads like an expensive copy.
- Try
&Tfirst and reach forRc<T>when you hit a lifetime you cannot express. "I cannot prove who dies last" is the honest test for whether reference counting is warranted.
- Own downwards with
Rcand point backwards withWeak. Deciding which direction owns, once, up front, prevents every cycle you would otherwise have to debug.
- Keep the value inside an
Rcimmutable when you can. A shared read-only lookup table is the caseRcis best at, and it needs no interior mutability at all.
- Ask
Rc::ptr_eqwhen the question is "the same allocation" and==when the question is "the same value". They are different questions and mixing them up produces bugs that only appear with duplicate data.
- Use
strong_countandweak_countfreely in tests -- they make ownership assertions possible that would otherwise be untestable -- and keep them out of production control flow.
- Prefer
RcoverArcwhile you are genuinely single-threaded, and swap when you cross a thread boundary rather than pre-emptively.
- Draw the ownership graph on paper before adding a second
Rcfield to a struct. Cycles are easy to see in a drawing and nearly invisible in code.
Practice Exercises
- Print
Rc::strong_countat five points in one program: after creation, after two clones, inside a nested scope, after that scope ends, and after an explicitdrop. Predict every number before running it, and account for any you got wrong.
- Build the cycle deliberately: a
ParentholdingVec<Rc<Child>>and aChildholdingOption<Rc<Parent>>, with aDropimpl printing on both. Confirm neither destructor runs, then change the child's field toWeakand confirm both do.
- Take the worked example and replace
Rc<Rates>with&Rates. Get it compiling insidemain, then move the booking construction into a function that returns theVecand write down the exact error you get.
- Try to move a
Bookinginto astd::thread::spawnclosure. Record the error, name the missing trait, and say which single type in the struct is responsible.