Zeeshan Adil
Book a call
← Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes

Chapter 11 of 16 · Part III, Concurrency and systems

Interior mutability, or breaking the rules on purpose

by Zeeshan AdilUpdated 28 min read
Listen to this articleRust Rc, RefCell and Cell: Interior Mutability for C# Devs 30 min · read by an AI voice
0:00 / 29:36

When one owner and one writer is not enough: Rc, Cell, RefCell and Weak, reference cycles, arenas and indices, and where a C# garbage collector simply wins.

Start with ordinary borrowing and Drop already in mind. This chapter separates shared ownership (Rc) from checked mutation (RefCell) and shows why cycles matter. Understand those two jobs before combining the types or comparing arena designs.

One owner and one writer is a clean model, and some real designs do not fit it. A graph where nodes reference each other. An observer list where several places hold the same subject. A cache shared by every request handler. A parse tree where a child needs to ask its parent a question.

C# makes shared object references easy to express, although the design still needs to control mutation and lifetime. Rust asks you to make those choices explicit in the types.

The asking is the part worth understanding. Rust does not have a back door bolted on for awkward cases. It has a single, tiny, compiler-known primitive, and every safe abstraction that lets you mutate through a shared reference is built on top of it. The Rust Reference is blunt about this: UnsafeCell<T> is the only allowed way to mutate through a shared reference, and everything else in std::cell is a wrapper around it that adds a rule the wrapper can enforce itself.

Picking one of those wrappers is picking which rule you want enforced, and where the enforcement happens.

What the compiler gives up

&T in Rust carries an address and a promise. The promise is that for the life of that reference, the pointed-at value does not change. LLVM gets told this, roughly as noalias and readonly, and it uses it: it can hoist a load out of a loop, keep a field in a register across a call, and skip a reload after a store through some unrelated pointer.

UnsafeCell<T> is the switch that turns that assertion off for one field. It is a lang item, so the compiler knows about it specifically, and the moment a UnsafeCell is in the type, the "this does not change" claim is withdrawn for the memory it covers.

That is the real cost of interior mutability, and it is easy to miss because it never shows up as a line item. You pay a borrow flag or a counter, yes, but you also pay in optimizations that quietly stop happening. In practice this is small. In a hot loop over a RefCell it is not always small.

The design goal is worth naming. The C++ answer to shared mutable state is "be careful". The C# answer is "the runtime will keep it alive and you should probably take a lock". Rust's answer is to make the escape hatch a type, so that a reader can see it in the signature, the optimizer can see it in the layout, and there is exactly one place to look when something goes wrong.

Shared ownership, and what the count actually is

Rc<T> is a reference-counted pointer. Cloning it bumps a counter instead of copying the data, and the value is dropped when the last handle goes away.

Code
use std::rc::Rc;

let config = Rc::new(Config::load());
let a = Rc::clone(&config);   // count is 2
let b = Rc::clone(&config);   // count is 3
// value dropped when the last of config, a and b goes out of scope

This is the closest thing Rust has to what a garbage collector gives you, done eagerly and locally. Rc::clone(&x) and x.clone() do the same thing; the community convention is the explicit form, so that a reader scanning for expensive clones can tell at a glance that this one is not.

The simple model is "there is a counter". The real thing is two counters, and the difference matters later in this chapter. A new allocation in the current standard library looks like this:

Code
struct RcInner<T: ?Sized> {
    strong: Cell<usize>,
    weak: Cell<usize>,
    value: T,
}

strong counts the Rc handles. When it hits zero, T is dropped, immediately, on whichever line released the last handle. weak counts the Weak handles plus one, because all the strong handles collectively hold a single weak reference between them; when weak hits zero the allocation itself is freed. That is why Rc::weak_count returns the internal weak count minus one, and it is why a Weak can safely check whether the value is still there without the block having been freed underneath it.

Both counters are Cell<usize>, not atomics. That is what makes Rc cheap: an increment and a decrement with no bus lock, no memory fence. It is also what makes Rc single-threaded only, enforced at compile time, which is the subject of the next chapter.

The Rc handle you hold is one pointer wide. The overhead is in the allocation: two usize of header on a 64-bit target, so 16 bytes per shared value regardless of how big the value is. For a shared config loaded once, irrelevant. For 100,000 tree nodes, 16 bytes each is 1.6 MB of pure bookkeeping before you have stored anything.

Now the part that surprises people. Rc<T> gives you shared ownership, and shared ownership only ever gives you shared access:

Code
use std::rc::Rc;

let shared = Rc::new(vec![1, 2, 3]);
let _other = Rc::clone(&shared);
shared.push(4);
Code
error[E0596]: cannot borrow data in an `Rc` as mutable
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Vec<i32>>`

Rc implements Deref and deliberately does not implement DerefMut, because it cannot know whether some other handle is reading right now. Every C# instinct you have says this should work. It does not, and the error above is the language telling you that shared ownership and mutation are two separate permissions here, and it only handed you one.

Cell, when you only ever swap the value

Cell<T> is the version with no borrowing at all. Through a &Cell<T> you can never obtain a &T to the value inside. You move values in and out, which means there is no borrow to conflict with anything, which means there is nothing to panic about.

Code
use std::cell::Cell;

struct Metrics {
    hits: Cell<u64>,
    misses: Cell<u64>,
}

impl Metrics {
    fn record(&self, hit: bool) {          // note: &self, not &mut self
        if hit {
            self.hits.set(self.hits.get() + 1);
        } else {
            self.misses.set(self.misses.get() + 1);
        }
    }

    fn hit_rate(&self) -> f64 {
        let h = self.hits.get() as f64;
        let m = self.misses.get() as f64;
        if h + m == 0.0 { 0.0 } else { h / (h + m) }
    }
}

The C# version of this is unremarkable, which is exactly the point:

Code
sealed class Metrics
{
    private long _hits;
    private long _misses;

    public void Record(bool hit)
    {
        if (hit) _hits++; else _misses++;
    }

    public double HitRate =>
        _hits + _misses == 0 ? 0 : (double)_hits / (_hits + _misses);
}

C# has no shared-versus-exclusive distinction on references, so there is nothing to opt out of. In Rust, Cell is what lets record take &self, which in turn is what lets Metrics sit inside an Rc, get borrowed by three call sites, and still count things. Without it you would have to thread &mut Metrics through every layer, and that is the kind of change that ripples through an entire call graph.

One correction to the shorthand you will see everywhere. Cell<T> is not restricted to Copy types. set, replace, swap and into_inner work for any T. It is get that needs T: Copy, because get copies the value out and leaves the original in place, and that is only sound for types where a bitwise copy is a valid duplicate. For a Cell<String> you use replace or take and put something back.

If you are on Rust 1.88 or newer, Cell::update collapses the get-modify-set dance into self.hits.update(|n| n + 1). On anything older, write it out.

RefCell, and the borrow check at run time

RefCell<T> keeps the borrowing rules and moves the enforcement from compile time to run time.

Code
use std::cell::RefCell;

let counter = RefCell::new(0);
*counter.borrow_mut() += 1;              // exclusive borrow, released at end of statement
println!("{}", counter.borrow());        // shared borrow

The mechanism is a single isize sitting next to your value. Zero means unborrowed, a positive value counts live shared borrows, a negative value counts live exclusive ones. borrow() returns a Ref guard that reduces the shared count on drop. Dropping a RefMut moves the negative count back toward zero; split guards can represent disjoint mutable borrows. If the flag says the request is not allowed, it panics.

The rule has not changed. Any number of readers, or exactly one writer. Only the moment of enforcement moved, and with it the failure mode: you traded a compile error for a possible crash, in exchange for expressing a shape the static checker could not verify.

The failure is worth seeing in all three forms, because you have already met two of them.

In C#, this compiles and throws:

Code
var entries = new List<long> { 10, 20 };
foreach (var e in entries)
{
    if (e > 15) entries.Add(e / 2);
}
// System.InvalidOperationException:
// Collection was modified; enumeration operation may not execute.

In Rust with a plain Vec, the same shape does not compile at all. That is error[E0502], and the borrowing chapter covered it.

In Rust with a RefCell, it compiles, and then it does this:

Code
use std::cell::RefCell;

struct Ledger {
    entries: Vec<i64>,
}

fn split_large(ledger: &RefCell<Ledger>) {
    let view = ledger.borrow();                       // shared borrow, held by `view`
    for e in view.entries.iter() {
        if *e > 15 {
            ledger.borrow_mut().entries.push(*e / 2); // wants exclusive access
        }
    }
}

fn main() {
    let ledger = RefCell::new(Ledger { entries: vec![10, 20] });
    split_large(&ledger);
    println!("{:?}", ledger.borrow().entries);
}
Code
thread 'main' (0x37f8) panicked at src/main.rs:11:20:
RefCell already borrowed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Line 11 column 20 is the borrow_mut call, not a line inside the standard library, because borrow and borrow_mut are marked #[track_caller]. Without that you would get a location inside cell.rs, which tells you nothing about which of your call sites did it.

A C# List<T> enumerator normally checks a version counter during iteration, subject to optimization. Rust's borrow checker rejects the direct Vec example at compile time. RefCell instead checks at borrow time and panics on a conflict. A panic may unwind the current thread or task; it does not necessarily terminate the whole process.

Three habits keep RefCell panics out of your codebase, and they are all the same habit.

Never hold a borrow across a call you do not control. The panic above happens because view is alive when borrow_mut runs. Compute first, mutate second:

Code
fn split_large(ledger: &RefCell<Ledger>) {
    let extra: Vec<i64> = ledger
        .borrow()
        .entries
        .iter()
        .filter(|e| **e > 15)
        .map(|e| e / 2)
        .collect();                              // borrow ends with this statement
    ledger.borrow_mut().entries.extend(extra);
}

Keep borrows to a single statement or an explicit small block. A Ref bound to a let lives until the end of its scope. A Ref produced as a temporary inside an expression dies at the end of that statement. The second is much harder to get wrong, and when you genuinely need a named guard, wrap it in braces so the scope is visible.

Use try_borrow_mut at re-entrancy boundaries. It returns a Result instead of panicking. If you are writing anything callback-shaped, an event bus, a plugin host, a component that invokes user code, this is the difference between degrading and dying. The panic is not a bug in your data structure, it is a re-entrancy report, and sometimes the right response is to queue the work rather than to abort.

Rc of RefCell is roughly a C# object reference

Put the two together and you get the pattern that shows up in every Rust codebase that models a graph:

Code
use std::cell::RefCell;
use std::rc::Rc;

type Shared<T> = Rc<RefCell<T>>;

let subscribers: Shared<Vec<String>> = Rc::new(RefCell::new(Vec::new()));
let handle = Rc::clone(&subscribers);
handle.borrow_mut().push("alerts".to_string());

Rc<RefCell<T>> is, roughly, a C# object reference. Shared, mutable, reference-counted rather than traced. Say it out loud, because that is the honest description and pretending otherwise wastes people's time.

It is not free, and the arithmetic is easy. On a 64-bit target you are paying two usize for the Rc header and one isize for the borrow flag, so 24 bytes of overhead per shared value plus alignment padding, one allocation each, and a branch on every access. And you gave up something the type system was doing for you: Rc<RefCell<T>> tells a reader nothing about who can write or when, which is precisely the information Rust normally hands you for free in a signature.

When you find yourself writing it everywhere, that is worth noticing. It usually means the design is fighting the language rather than the language failing the design. The fourth chapter of Learning Rust With Entirely Too Many Linked Lists is titled "A Bad Safe Deque" and spends its length demonstrating exactly this, on the smallest possible data structure, and it is worth an hour.

Cycles, and the one place a garbage collector simply wins

Rc cannot collect cycles. This is not a Rust shortcoming so much as a property of reference counting itself, and it applies equally to C++'s shared_ptr and to Python's counting layer before its cycle collector runs.

Code
use std::cell::RefCell;
use std::rc::Rc;

struct Session {
    id: u32,
    peer: RefCell<Option<Rc<Session>>>,
}

impl Drop for Session {
    fn drop(&mut self) {
        println!("dropping session {}", self.id);
    }
}

fn main() {
    {
        let a = Rc::new(Session { id: 1, peer: RefCell::new(None) });
        let b = Rc::new(Session { id: 2, peer: RefCell::new(None) });

        *a.peer.borrow_mut() = Some(Rc::clone(&b));
        *b.peer.borrow_mut() = Some(Rc::clone(&a));

        println!("a strong = {}", Rc::strong_count(&a));
        println!("b strong = {}", Rc::strong_count(&b));
    }
    println!("scope ended");
}
Code
a strong = 2
b strong = 2
scope ended

No "dropping session" line, ever. At the closing brace, a and b go out of scope and each count drops from 2 to 1. Neither reaches zero, because each object is being held alive by the other. Drop never runs and the memory is never freed.

The compiler will not say a word about it. Nothing in the type system models "this graph has a loop in it". Miri does catch it, because it checks at the end of a run for allocations that are no longer reachable from a static and reports "the evaluated program leaked memory", so running your tests under Miri is a real defense here. That is a test-time tool, though, not a compile-time one, and it only sees the paths your tests take.

.NET does not have this problem, and it is not close. The collector works from roots: static fields, thread stacks, registers, GC handles. It builds the graph of everything reachable from those roots, and anything not in that graph is garbage. A cycle floating free of every root is unreachable by definition, so it is collected like anything else, and you never think about it. Reachability is a global property, and a tracing collector computes global properties. A reference count is a local one, and local counts cannot see a loop.

This is genuinely the place where the .NET model is better, full stop. Not "better if you squint", not "a different set of tradeoffs". If your data is a real graph with real cycles and it churns, a tracing collector is doing work for you that Rust is going to make you do by hand.

Two honest qualifications. First, leaking memory is safe in Rust, deliberately: mem::forget and Rc cycles are both allowed, because leaks cannot corrupt anything. Rust's safety promise was never "no leaks". Second, in practice this bites less often than it sounds, because the fix is usually a change in modeling rather than a change in machinery.

Weak, and a tree that actually works

Weak<T> is a non-owning handle. It does not contribute to the strong count, so it cannot keep a value alive, and you cannot use it directly. You call upgrade, which returns Option<Rc<T>>: Some if the value is still there, None if the last strong handle has gone.

The standard shape for a tree is: parents own children with Rc, children point back at parents with Weak. Here is the whole thing, runnable.

Code
use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Node {
    name: String,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

impl Node {
    fn new(name: &str) -> Rc<Node> {
        Rc::new(Node {
            name: name.to_string(),
            parent: RefCell::new(Weak::new()),
            children: RefCell::new(Vec::new()),
        })
    }

    fn add_child(parent: &Rc<Node>, child: Rc<Node>) {
        *child.parent.borrow_mut() = Rc::downgrade(parent);
        parent.children.borrow_mut().push(child);
    }

    fn path(&self) -> String {
        match self.parent.borrow().upgrade() {
            Some(p) => format!("{}/{}", p.path(), self.name),
            None => self.name.clone(),
        }
    }
}

fn main() {
    let root = Node::new("root");
    let services = Node::new("services");
    let db = Node::new("db");

    Node::add_child(&root, Rc::clone(&services));
    Node::add_child(&services, Rc::clone(&db));

    println!("{}", db.path());
    println!("root:     strong={} weak={}", Rc::strong_count(&root), Rc::weak_count(&root));
    println!("services: strong={} weak={}", Rc::strong_count(&services), Rc::weak_count(&services));
    println!("db:       strong={} weak={}", Rc::strong_count(&db), Rc::weak_count(&db));

    drop(root);
    println!("after dropping root, db.path() = {}", db.path());
}
Code
root/services/db
root:     strong=1 weak=1
services: strong=2 weak=1
db:       strong=2 weak=0
after dropping root, db.path() = services/db

Read the counts. services has a strong count of 2 because the local binding and the vector inside root both own it. root has a strong count of 1 and a weak count of 1, the weak one being the back pointer from services. db has no children so nothing points weakly at it.

Then drop(root) runs, the strong count reaches zero, and the whole Node is destroyed, including its children vector, which takes services from 2 down to 1. The Weak inside services is now dangling in the logical sense, and the last line proves it handles that gracefully: upgrade returns None, path stops walking, and you get services/db instead of a crash.

The C# version does not need any of this:

Code
sealed class Node
{
    public string Name { get; }
    public Node? Parent { get; private set; }
    public List<Node> Children { get; } = new();

    public Node(string name) => Name = name;

    public void AddChild(Node child)
    {
        child.Parent = this;
        Children.Add(child);
    }

    public string Path() => Parent is null ? Name : $"{Parent.Path()}/{Name}";
}

Count the two listings: 16 lines of C# against 27 lines of Rust for the same type, and the C# needed no design decisions to get there. That gap is real and you should not talk yourself out of noticing it.

But notice the semantic difference too, because it is not only ceremony. In C#, db holding a Parent reference keeps root alive for as long as db is alive. The whole tree is one reachability unit; drop your reference to the root and nothing is collected until every node is unreachable. In Rust, the Weak back pointer says explicitly that children do not own their parents, so dropping the root really does free the root, and children discover it. Whether that is what you want is a design decision. Rust made you make it. C# made it for you.

Arenas and indices, which is usually the better answer

Now the opinion. Reaching for Rc<RefCell<T>> at the first borrow error is almost always the wrong move, and it is the most common way a C# engineer's first Rust codebase ends up worse than the C# it replaced.

Before you reach for it, try restructuring so that ownership is a tree and everything else holds an index into a central Vec. For graphs specifically, an arena with integer ids is usually simpler, faster and much easier to debug than a web of counted pointers.

Here is the same tree stored in an arena. Indices do not own nodes, so cycles in the links cannot create reference-count leaks:

Code
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct NodeId(usize);

struct Node {
    name: String,
    parent: Option<NodeId>,
    children: Vec<NodeId>,
}

#[derive(Default)]
struct Tree {
    nodes: Vec<Node>,
}

impl Tree {
    fn add(&mut self, name: &str, parent: Option<NodeId>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(Node {
            name: name.to_string(),
            parent,
            children: Vec::new(),
        });
        if let Some(p) = parent {
            self.nodes[p.0].children.push(id);
        }
        id
    }

    fn path(&self, id: NodeId) -> String {
        let node = &self.nodes[id.0];
        match node.parent {
            Some(p) => format!("{}/{}", self.path(p), node.name),
            None => node.name.clone(),
        }
    }

    fn rename_subtree(&mut self, id: NodeId, suffix: &str) {
        let mut stack = vec![id];
        while let Some(current) = stack.pop() {
            self.nodes[current.0].name.push_str(suffix);
            stack.extend(self.nodes[current.0].children.iter().copied());
        }
    }
}

fn main() {
    let mut tree = Tree::default();
    let root = tree.add("root", None);
    let services = tree.add("services", Some(root));
    let db = tree.add("db", Some(services));
    let cache = tree.add("cache", Some(services));

    println!("{}", tree.path(db));
    println!("{}", tree.path(cache));

    tree.rename_subtree(services, "-v2");
    println!("{}", tree.path(db));
}
Code
root/services/db
root/services/cache
root/services-v2/db-v2

This version removes reference counts and dynamic borrow flags. rename_subtree mutates through &mut self, so access is checked statically. The node records share a contiguous allocation, which can improve locality, although each child vector has its own storage and traversal still follows indices. An index can be invalid, and links can still form a logical cycle; validate them or track visited nodes when an API allows arbitrary edges.

This is not a Rust trick. It is the same technique you already reach for in C# when a List<T> of structs and integer indices beats a graph of class instances, and for the same reasons: fewer allocations, better locality, and a gen2 collection that has far fewer objects to mark. Rust just makes the alternative annoying enough that you find this one sooner.

The honest downside is real and you should hear it before you go and rewrite something. An index is not a reference, and the compiler stops helping you. If you remove a node and reuse the slot, an old NodeId now silently addresses a different node. That is a logic bug, not a memory-safety bug, so the program will not crash, it will just be wrong, which can be difficult to diagnose.

The standard answer is a generational index: store a generation counter alongside each slot and put the generation in the id, so a stale id fails to resolve instead of resolving to a stranger. slotmap does this and is the crate to reach for; petgraph::Graph also uses indices into graph storage, but those indices are not generational handles: removing a node can change another node's index. Choose the storage model according to the stability guarantees you need.

The pattern has been written up for a decade; Niko Matsakis wrote the canonical explanation in 2015, and Catherine West's RustConf 2018 keynote made the case at length for game entity systems, which is where the shape gets its worst-case workout.

There is one thing indices cost you that is easy to overlook: the arena has to be reachable everywhere you want to resolve an id. That means threading &Tree or &mut Tree through your call graph, and if your API surface makes that awkward, you will feel it. That awkwardness is usually a signal that the traversal logic belongs on the arena rather than on the node, which tends to be a better design anyway, but it is a real refactor and not a free one.

What this looks like once the system is real

At small scale none of this matters and you should not agonize over it. It starts mattering in three specific places.

Single-threaded servers and interpreters. Anything with a per-thread world, an event loop, a script host, a compiler pass, ends up with a lot of shared mutable state that never crosses a thread. Rc<RefCell<T>> is genuinely the right call here, and it is what the alternative would be in any other language too. The failure mode at scale is not memory, it is that borrow panics start appearing in production from re-entrancy paths nobody tested: a handler that fires a callback that touches the same store. That is when try_borrow_mut and a deferred work queue stop being pedantic.

Thread-local state. thread_local! with RefCell is a useful standard-library pattern. with_borrow and with_borrow_mut keep a borrow inside a closure, making its scope easier to see. Re-entering the same cell with a conflicting borrow can still panic; the helpers do not eliminate that possibility.

Large object graphs. This is where the arena pulls ahead by a lot, and where the two runtimes' costs finally diverge in the same direction. A million Rc<RefCell<Node>> values means a million allocations, 24 bytes of overhead each before padding, and pointer chasing on every traversal. The equivalent .NET object graph is cheaper to write, but the collector's mark work scales with the number of live objects, so a big long-lived graph is the shape that gen2 has to keep re-walking. Be fair about the mitigation: background GC is on by default and does most of that gen2 marking on dedicated threads, so this shows up as CPU spent rather than as long stop-the-world pauses. The work is still proportional to the graph. Both runtimes reward the same fix: fewer, larger, flatter allocations.

The two habits that spread Rc through a codebase

Reaching for Rc<RefCell<T>> on the first borrow error. The symptom is a codebase where a Shared<T> alias has spread into every module and no signature tells you who writes what. The fix is almost always to make ownership a tree, pass &mut down instead of storing handles up, and use ids for anything that needs to point sideways.

Storing an Rc where a & would do. Sharing a value for the duration of a call is a borrow, not shared ownership. If the handle never outlives the caller, take &T and delete the Rc. This one is easy to spot: an Rc cloned only for the duration of a call may be replaceable with a borrow. Cloning the handle increments its count; it does not allocate a new copy of the value.

Assuming a borrow ends where the expression ends. let g = cell.borrow(); holds until the end of the scope, not the end of the line. C# has scope-bound cleanup too, in using and lock, but it is always announced by a keyword, so there is no habit of reading a plain local declaration as something that holds a resource open. Treat borrow() the way you treat a lock block, and give it explicit braces.

Expecting Weak to behave like WeakReference<T>. They are spelled similarly and solve different problems. .NET's WeakReference<T> exists so a cache can let the collector reclaim entries under memory pressure; it is a hint to a collector that is already handling your cycles. Rust's Weak exists to break ownership cycles that would otherwise leak, and it is load-bearing rather than advisory. Using Weak for caching in Rust mostly does not make sense, because nothing is going to come along and reclaim things for you.

Treating a borrow panic as a bug in RefCell. It is not. It is your program telling you that two code paths wanted the same value at the same time, which is information you would not have had in C#, where the second path would have quietly seen a half-updated object. The panic is the diagnosis, not the disease.

Two places the collector simply wins

Two places, and neither is a close call.

Cyclic object graphs that change shape at run time. Covered above. A tracing collector computes reachability globally and reference counting cannot. If you are modeling something genuinely graph-shaped and mutable, .NET does this correctly for free and Rust makes you design for it. Say so in a code review rather than defending the language.

Prototyping speed on anything object-shaped. The C# node class above required no decisions. The Rust version forces three: which direction ownership runs, Rc or an arena, and what happens when a parent is gone. Those are good decisions to have made by the time the thing ships, and terrible ones to be forced into on day one when the shape of the problem is still unknown. If you are exploring, explore in the language that lets you.

For most application code this whole section is a footnote, because ownership really is a tree and none of the machinery ever comes up. Interior mutability is not an advanced technique to graduate into. It is a specific tool for a specific shape, and the shape is rarer than the amount of writing about it suggests.

Checking yourself

Why does Rc<T> refuse to give you a &mut T, when it clearly knows how many handles exist?

Because knowing the count is not enough. Another handle could be reading right now, somewhere up the call stack, and Rc has no way to see that. It only implements Deref, never DerefMut. Rc::get_mut is the exception, and it works precisely because it refuses unless the count is 1 and there are no Weak handles, at which point no other reader can exist.

A RefCell panics with "RefCell already borrowed". What does that tell you about your code, and what does it not tell you?

It tells you a borrow_mut was requested while a conflicting Ref or RefMut guard was still alive. Thanks to #[track_caller] you get the location of the failing call. It does not tell you where the conflicting borrow was taken, which is the piece you usually want, so look for a let binding holding a guard across the failing call, or a re-entrant callback.

Two nodes hold Rc handles to each other and go out of scope. What happens, and what would .NET do?

Both counts drop to 1 rather than 0, so neither value is dropped, Drop never runs, and the allocation leaks. .NET would collect both, because neither is reachable from a root and the collector works from reachability rather than from counts. This is the clearest case where a tracing collector is simply better.

You have a hundred thousand nodes with parent and child links. What do you build?

An arena is worth considering: store nodes together and use indices for links. That avoids ownership-cycle leaks and can improve locality. It does not prevent logical cycles or guarantee sequential traversal. If slots can be removed and reused, generational handles such as those in slotmap help detect stale references.

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.