skip to content

In Rust, why model shared bank accounts as `Rc<RefCell<Account>>`, and what does each of the two layers contribute?

level: middleimportance: must knowfreq 70%

answer

  1. Rc shares, RefCell mutates
  2. Rc dereferences to &T only
  3. E0594 through a bare Rc
  4. borrow_mut through any handle
  5. same account on both sides

basics

~20 s

Rc<T> gives one value several owners but only lends &T, so assigning through it fails with E0594. RefCell<T> adds mutation through that &T, checked at run time. Together they give many handles, each able to borrow_mut the account, on one thread.

solid answer

~40 s

`Rc<Account>` lets a ledger, a customer and a statement all hold the same account, and `Rc::clone` only bumps a count. But `Rc` implements `Deref`, not `DerefMut`, so `b.balance += 1` is rejected with E0594, "cannot assign to data in an `Rc`". Wrapping the account in a `RefCell` restores mutation: `account.borrow_mut().balance -= 30` works through any handle, with the borrow rules checked at run time. The combination adds runtime bookkeeping in both layers, carries a panic risk, and is single-threaded, because `Rc` is not `Send` and `RefCell` is not `Sync`. The classic bug is `transfer(from, to)` called with the same account twice: the second `borrow_mut()` panics with `RefCell already borrowed`, so guard it with `Rc::ptr_eq(from, to)`.

code

rust · 29 lines
rust
use std::cell::RefCell;
use std::rc::Rc;

struct Account {
    name: &'static str,
    balance: i64,
}

type Shared = Rc<RefCell<Account>>;

fn transfer(from: &Shared, to: &Shared, amount: i64) {
    let mut src = from.borrow_mut();
    let mut dst = to.borrow_mut(); // panics when `to` is the same RefCell as `from`
    src.balance -= amount;
    dst.balance += amount;
}

fn main() {
    let alice: Shared = Rc::new(RefCell::new(Account { name: "alice", balance: 100 }));
    let bob: Shared = Rc::new(RefCell::new(Account { name: "bob", balance: 50 }));
    let alice_in_ledger = Rc::clone(&alice); // second handle, same account

    transfer(&alice, &bob, 30);
    println!("{} {}", alice.borrow().name, alice.borrow().balance);
    println!("{} {}", bob.borrow().name, bob.borrow().balance);
    println!("strong = {}", Rc::strong_count(&alice));

    transfer(&alice, &alice_in_ledger, 10); // self-transfer
}

go deeper

for a junior

Recall the split: Rc gives several owners but only shared access; RefCell adds mutation through that shared access, checked at run time.

for a middle

Explain why a bare Rc fails with E0594, why the order is Rc<RefCell<T>>, and how the same-account transfer panics without an Rc::ptr_eq guard.

for a senior

Show the costs you would weigh in review: runtime panics instead of compile errors, single-thread only, and cycle leaks that call for Weak back-references.

for a principal

Be ready to argue when a single owner with &mut self, such as a Bank owning a Vec of accounts, should replace a web of Rc<RefCell<Account>> handles.

## Shared and mutable at the same time A bank-account graph has two needs that Rust's defaults keep apart. Several parts of the program must **hold the same account**: the ledger, each customer record, a pending statement. And transfers must **change** that account's balance. Single ownership with `&mut` cannot express the first; plain shared references cannot express the second. `Rc<RefCell<Account>>` splits the job between two types. ## Layer one: `Rc<T>` for shared ownership `std::rc::Rc<T>` puts the value in a heap allocation with a reference count. `Rc::clone(&a)` returns another handle to the **same** allocation and increments the strong count; it does not copy the `Account`. The value is dropped when the last handle goes. The details of counts, `Weak` and cycles are covered with `Rc` itself. What matters here is what `Rc` lends. It implements `Deref<Target = T>` but not `DerefMut`, because any number of handles may exist and a `&mut T` must be unique. So mutation through a bare `Rc` does not compile: ```rust let a = Rc::new(Account { balance: 1 }); let b = Rc::clone(&a); b.balance += 1; // error[E0594]: cannot assign to data in an `Rc` ``` rustc adds the help line: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Account>`. ## Layer two: `RefCell<T>` for mutation through `&` `RefCell<T>` provides **interior mutability**: `borrow_mut(&self)` returns a `RefMut<Account>` that dereferences to `&mut Account`, after checking at run time that no other borrow of this cell is live. Because `Rc` hands out `&RefCell<Account>`, every handle can now call `borrow_mut()`: - `alice.borrow().balance` reads through a `Ref` guard. - `alice.borrow_mut().balance -= 30` writes through a `RefMut` guard. - The guard's drop at the end of the statement gives the borrow back. The order matters. `Rc<RefCell<T>>` means "shared, and the shared value is mutable". `RefCell<Rc<T>>` means "one owner can swap which `Rc` it holds", while the account behind that `Rc` stays read-only. ## What the combination costs | Cost | Source | |---|---| | strong and weak counts per allocation | `Rc` | | a borrow counter checked on every borrow | `RefCell` | | aliasing mistakes become panics, not compile errors | `RefCell` | | cannot be moved to another thread | `Rc` is `!Send` | | cannot be shared by reference across threads | `RefCell` is `!Sync` | | leaks if handles form a cycle | `Rc` | The cross-thread equivalent is `Arc` with `Mutex` or `RwLock`, covered with threads and locks. ## The same-account transfer A transfer function typically borrows both accounts mutably: ```rust fn transfer(from: &Shared, to: &Shared, amount: i64) { let mut src = from.borrow_mut(); let mut dst = to.borrow_mut(); src.balance -= amount; dst.balance += amount; } ``` This works for two different accounts. When `from` and `to` are two handles to **one** account, for example `alice` and `Rc::clone(&alice)` taken from the ledger, `src` is a live `RefMut` and the second `borrow_mut()` panics with `RefCell already borrowed`. With `&mut` references the compiler would have rejected the aliasing with E0499; with `Rc<RefCell<T>>` nothing stops it until run time. The fixes: 1. **Compare identities first.** `Rc::ptr_eq(from, to)` returns `true` when both handles point at the same allocation; treat that case as a no-op or an error before borrowing. 2. **Never hold one guard while borrowing another cell that might be the same.** Writing `from.borrow_mut().balance -= amount;` and then `to.borrow_mut().balance += amount;` drops each `RefMut` at its semicolon, so the self-transfer no longer panics; this works only when no check must span both accounts. 3. **Prefer a single owner when transfers are central.** A `Bank` that owns a `Vec<Account>` and takes `&mut self` lets the compiler prove exclusivity; that design trade-off is a lead's call. ## Other pitfalls - Holding a `RefMut` while calling a method that borrows the same account again panics on re-entry. - An account that stores `Rc` handles back to its owners creates a cycle; use `Weak` for back-references. - `Rc::clone` is cheap, but each clone is one more place that can borrow, so keep the set of handles small and obvious.

  • Why not use `RefCell<Rc<Account>>` instead?
    It mutates the wrong thing. `RefCell<Rc<Account>>` lets the one owner of the cell replace which `Rc` it holds, but the `Account` behind every `Rc` is still reachable only as `&Account`, so balances stay read-only. `Rc<RefCell<Account>>` shares the cell itself, so every handle can `borrow_mut()` the one account.
  • What exactly does `Rc::ptr_eq` compare?
    The addresses of the allocations, not the `Account` values. Two handles from `Rc::clone` of one account compare equal; two distinct accounts with identical fields compare unequal. That is exactly the question a transfer needs answered before taking two `RefMut` guards.
  • How would you share these accounts across threads?
    Not with this type: `Rc` is `!Send` because its counts are not atomic, and `RefCell` is `!Sync`. The thread-safe shape is `Arc` with a `Mutex` or `RwLock`, covered with threads and locks; there, locking the same account twice on one thread is not reported cleanly: the std docs say the second lock might panic or deadlock.

  • Rc<T> alone allows mutation because every owner holds a handle.
  • Rc::clone copies the account, so each handle mutates its own copy.
  • The compiler stops transfer from borrowing one account mutably twice.
  • Rc<RefCell<T>> can go to another thread whenever T is Send.
  • RefCell<Rc<T>> and Rc<RefCell<T>> are interchangeable spellings.