skip to content

As a Rust lead, when do you accept `Rc<RefCell<T>>` in a codebase, and when do you require restructuring ownership instead?

level: principalimportance: should knowfreq 34%

answer

  1. borrow errors move to run time
  2. who really owns this data?
  3. one owner plus typed indices
  4. pass &mut down, or send messages
  5. contain it behind a small API

basics

~20 s

Accept Rc<RefCell<T>> for genuinely shared, single-threaded state contained behind a small API, such as UI callbacks updating one model. When it spreads through domain types, require a single owner with indices, explicit &mut passing or messages, which keep the checks at compile time.

solid answer

~50 s

`Rc<RefCell<T>>` trades compile-time guarantees for flexibility: aliasing mistakes become `RefCell already borrowed` panics, ownership becomes an implicit graph, `Rc` cycles leak, and the type cannot cross threads. I accept it when sharing is real and local: several single-threaded callbacks updating one view model, a prototype graph, a parent-child tree with `Weak` back-links, provided it sits behind a module whose methods borrow briefly and never hold a guard across a callback. I require restructuring when it becomes the backbone of the domain model. A `Bank` that owns `Vec<Account>` and exposes `transfer(&mut self, from: AccountId, to: AccountId)` lets the borrow checker prove exclusivity, and the same-account case is a plain `if`. Other options are passing `&mut` down the call stack, or one task owning the state and receiving commands as messages. The rule I write down: no `RefCell` in public signatures, `Cell` for `Copy` flags, and every new `Rc<RefCell<T>>` justified in review.

code

rust · 38 lines
rust
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct AccountId(usize);

struct Account {
    owner: String,
    balance: i64,
}

struct Bank {
    accounts: Vec<Account>, // the bank is the single owner
}

impl Bank {
    fn open(&mut self, owner: &str, balance: i64) -> AccountId {
        self.accounts.push(Account { owner: owner.to_string(), balance });
        AccountId(self.accounts.len() - 1)
    }

    // &mut self: the borrow checker, not a runtime counter, proves exclusive access.
    fn transfer(&mut self, from: AccountId, to: AccountId, amount: i64) {
        if from == to {
            return;
        }
        self.accounts[from.0].balance -= amount;
        self.accounts[to.0].balance += amount;
    }
}

fn main() {
    let mut bank = Bank { accounts: Vec::new() };
    let alice = bank.open("alice", 100);
    let bob = bank.open("bob", 50);
    bank.transfer(alice, bob, 30);
    bank.transfer(alice, alice, 10); // same account: a plain branch, no panic
    for a in &bank.accounts {
        println!("{} {}", a.owner, a.balance);
    }
}

go deeper

for a junior

Recall that Rc<RefCell<T>> means shared and mutable on one thread, and that its borrow mistakes show up as panics rather than compile errors.

for a middle

Explain the concrete costs: runtime borrow panics, Rc cycles that need Weak, and no path to threads without changing to Arc and a lock.

for a senior

Show you can restructure a Rc<RefCell<T>> design into a single owner with typed ids or &mut passing, and say where that refactor is not worth it.

for a principal

Own the rule: when shared mutable handles are acceptable, how they are contained, and how the team reviews new ones, weighing speed of writing against cost of failure.

## What `Rc<RefCell<T>>` trades away `Rc<RefCell<T>>` is the standard library's answer to "several owners, all of whom may mutate, on one thread". It works, and it compiles in places where nothing else seems to. A lead's question is not whether it works but what the team gives up each time it appears: - **Compile-time aliasing checks become runtime panics.** A double `borrow_mut()` that `&mut` would have rejected with E0499 now ships and panics with `RefCell already borrowed`, possibly on a rare path. - **Ownership becomes implicit.** Any holder of a handle can mutate, so "who changes this balance?" is answered by grep rather than by signatures. - **Cycles leak.** `Rc` handles that point at each other are never freed unless back-references use `Weak`. - **It is single-threaded by construction.** `Rc` is `!Send` and `RefCell` is `!Sync`; moving to threads means rewriting to `Arc` with `Mutex` or `RwLock`, where the same mistakes can become deadlocks. - **It spreads.** Once one type holds `Rc<RefCell<_>>`, the types around it tend to follow. ## Where it earns its place There is no single right answer; the call depends on how real and how local the sharing is. Reasonable cases: - Several single-threaded UI or event callbacks that each need to update one shared model. - A tree with owned children and `Weak` parent links, where the shape is genuinely a graph of independent lifetimes. - Prototypes and tests where speed of change matters more than the guarantees. - Integration with a callback-driven API that hands you only `&self` or `'static` closures. In each case the condition is **containment**: the `Rc<RefCell<T>>` lives inside one module, its methods take a borrow for one statement, and no guard is held while calling out to code that might re-enter. ## The alternatives a lead should name | Approach | How it works | What stays compile-time checked | Cost | |---|---|---|---| | Single owner plus indices | one struct owns a `Vec<T>`; others hold typed ids | exclusivity via `&mut self` | stale ids are a logic bug, not undefined behaviour | | Pass `&mut` down | callers lend mutable access for the call | everything | longer parameter lists; deep call chains | | Message passing | one owner task applies commands from a queue | the owner's mutation | indirection, asynchronous replies | | Split state | separate the shared read-only part from the mutable part | most of it | design effort up front | | `Rc<RefCell<T>>` | shared handles, runtime borrow checks | nothing about aliasing | panics, leaks, single thread | Game code often reaches the indices approach through an entity-component system; services often reach the message approach through an actor or command queue. Both keep one owner per piece of state. ## A worked restructure: the ledger A ledger built from `Rc<RefCell<Account>>` handles needs an `Rc::ptr_eq` guard to stop a self-transfer from panicking, and nothing in the types tells a reviewer that. Restructured, the `Bank` owns every account and hands out `AccountId(usize)` values: ```rust fn transfer(&mut self, from: AccountId, to: AccountId, amount: i64) { if from == to { return; } self.accounts[from.0].balance -= amount; self.accounts[to.0].balance += amount; } ``` The `&mut self` receiver is the proof of exclusive access, checked at compile time; there is no counter and no panic path for aliasing. The remaining failure, an id out of range, panics on indexing rather than corrupting memory, and generational ids can catch reuse of a removed slot. ## A team rule you can enforce 1. **Default to restructuring.** A new `Rc<RefCell<T>>` in a domain type needs a sentence in the pull request explaining why single ownership does not fit. 2. **Keep it out of public signatures.** Expose methods, not `RefCell`; callers should not be able to hold a guard. 3. **One statement per borrow.** No `Ref` or `RefMut` held across a callback, an `.await` or a call back into the same module. 4. **Prefer the lightest cell.** `Cell` for `Copy` counters and flags, `OnceCell` for set-once values, `RefCell` only when you must borrow in place. 5. **Plan the thread story.** If the code may become multi-threaded, choose the single-owner or message design now, because `Rc<RefCell<T>>` does not migrate cleanly. The trade-off to articulate in an interview is speed of writing against cost of reading and of failure: `Rc<RefCell<T>>` is quick to write and expensive to reason about, and the lead's job is deciding where that trade is worth it.

  • How do you migrate an existing `Rc<RefCell<T>>` graph without a rewrite?
    Wrap it first: move every `borrow_mut()` behind methods on one owning type so guards never leave the module. Then change the storage inside that type to a `Vec` with typed ids, one entity kind at a time, keeping the method signatures. Callers stop seeing `RefCell` early, and the runtime checks disappear as each kind moves.
  • Isn't an index-based arena just raw pointers without safety?
    No. A stale or wrong id is a logic bug, but indexing a `Vec` out of range panics instead of reading freed memory, and a newtype such as `AccountId` stops ids of different kinds from mixing. Generational ids add a counter per slot so an id to a removed entry is detected rather than silently reused.

  • Rc<RefCell<T>> is always a code smell and should be banned outright.
  • If Rc<RefCell<T>> code compiles, it cannot fail at run time.
  • Index-based arenas are unsafe because ids bypass the borrow checker.
  • Switching to Arc<Mutex<T>> fixes the design problem behind Rc<RefCell<T>>.