skip to content

Cell and RefCell

Interior mutability lets you mutate through a shared reference, with Cell copying values in and out and RefCell checking borrows at run time. Interviewers ask when RefCell panics.

on this pageshow

questions

5

In Rust, when do you use `Cell<T>` rather than `RefCell<T>` for state that a `&self` method must change?

level: juniorimportance: must knowfreq 72%

answer

  1. copy in, copy out
  2. no reference into a Cell
  3. get needs Copy, take needs Default
  4. RefCell lends Ref and RefMut guards
  5. runtime borrow counter, panic on conflict

basics

~20 s

Cell<T> fits small values replaced whole, like a hit counter: it moves values in and out and never lends a reference. RefCell<T> lends &T or &mut T through guards, for a map or Vec, checking borrows at run time and panicking on conflict.

solid answer

~50 s

Both types give **interior mutability**: mutation through a shared `&self`. `Cell<T>` never hands out a reference to its contents. You copy a value out with `get` (only when `T: Copy`), write with `set` (which drops the old value), swap with `replace`, move out with `take` (when `T: Default`), or apply a closure with `update` (`T: Copy`, stable since Rust 1.88). Since no reference escapes, there is no borrow to track: no counter, no borrow check, no borrow-conflict panic. `RefCell<T>` lends the value in place: `borrow()` returns a `Ref<T>` guard, `borrow_mut()` a `RefMut<T>`, and a counter inside the cell enforces many readers or one writer at run time, panicking with `RefCell already borrowed` on a conflict. In a memoising calculator, the `u32` hit counter belongs in a `Cell` and the `HashMap` cache, which you must insert into, in a `RefCell`.

code

rust · 27 lines
rust
use std::cell::{Cell, RefCell};
use std::collections::HashMap;

struct Calculator {
    hits: Cell<u32>,                   // Copy value, replaced whole
    cache: RefCell<HashMap<u64, u64>>, // needs &mut HashMap to insert
}

impl Calculator {
    fn fib(&self, n: u64) -> u64 {
        if let Some(&v) = self.cache.borrow().get(&n) {
            self.hits.update(|h| h + 1); // Cell::update, stable since 1.88
            return v;
        }
        let v = if n < 2 { n } else { self.fib(n - 1) + self.fib(n - 2) };
        self.cache.borrow_mut().insert(n, v);
        v
    }
}

fn main() {
    let calc = Calculator { hits: Cell::new(0), cache: RefCell::new(HashMap::new()) };
    println!("fib(30) = {}", calc.fib(30));
    println!("cache hits = {}", calc.hits.get());
    println!("hits before reset = {}", calc.hits.take()); // u32: Default, so take() leaves 0
    println!("hits now = {}", calc.hits.get());
}

go deeper

for a junior

Recall the one-line split: Cell copies or moves whole values and never lends a reference; RefCell lends Ref and RefMut guards and panics on a conflicting borrow.

for a middle

Explain the method bounds: get and update need Copy, take needs Default, set and replace work for any type, and why lending no reference makes Cell check-free.

for a senior

Show you default to Cell for counters and flags to remove a panic path, and keep RefCell borrows short in hot paths where the counter check and panic risk matter.

for a principal

Frame cells as a last resort: a review rule that prefers &mut self or restructured ownership first, Cell second, RefCell third, keeps runtime-checked state rare and visible.

## Interior mutability in Rust Rust normally ties mutation to exclusive access: you change a value through `&mut T` or by owning it, and a shared `&T` is read-only. The standard library calls that **inherited mutability**. **Interior mutability** is the controlled exception: a type that may be mutated through `&T`. The cell types in `std::cell` provide it, and their module documentation calls them a tool of last resort, for things like caches inside logically read-only methods, counters inside `Clone` implementations, and state shared through `Rc`. The two everyday cells are `Cell<T>` and `RefCell<T>`. They solve the same problem with opposite strategies, and choosing between them is mostly a question of whether you need a **reference into** the value. ## `Cell<T>`: move values in and out `Cell<T>` never gives you a `&T` or `&mut T` to its contents while it is shared. Every operation moves or copies a whole value across the boundary: - `get()` returns a copy, so it exists only when `T: Copy`. - `set(val)` stores a new value and drops the old one; it works for any `T`. - `replace(val)` stores a new value and returns the old one; any `T`. - `take()` returns the value and leaves `Default::default()` behind, so it needs `T: Default`. - `update(f)` reads, applies a closure and writes back; it needs `T: Copy` and has been stable since **Rust 1.88**. - `into_inner()` consumes the cell, and `get_mut()` gives a `&mut T` when you already hold `&mut Cell<T>`. Because no reference into the cell can exist while it is shared, there is no aliasing to police. `Cell<T>` is `#[repr(transparent)]` over `UnsafeCell<T>`, so it has the same layout as `T`, and `get`, `set`, `replace` and `take` involve no runtime check at all. The cost is ergonomic: to change one field of a non-`Copy` value you must take it out, change it, and put it back. ## `RefCell<T>`: lend references, check at run time `RefCell<T>` lets you work on the value in place. `borrow()` returns a `Ref<'_, T>` guard that dereferences to `&T`; `borrow_mut()` returns a `RefMut<'_, T>` that dereferences to `&mut T`. The cell keeps a signed counter: positive while `Ref` guards are alive, negative while a `RefMut` is alive. Each call checks it, and a call that would break the rule "many readers or one writer" **panics**: `borrow_mut()` with the message `RefCell already borrowed`, `borrow()` with `RefCell already mutably borrowed`. The guard's `Drop` gives the borrow back. Non-panicking forms, `try_borrow()` and `try_borrow_mut()`, return a `Result` instead. ## Side by side | | `Cell<T>` | `RefCell<T>` | |---|---|---| | Access style | copy or move whole values | `Ref` / `RefMut` guards to the value in place | | Reading | `get()` needs `T: Copy` | `borrow()` works for any `T` | | Runtime cost | none beyond the copy | a counter update and check per borrow | | Borrow-conflict panic | none | on a conflicting borrow | | Typical contents | counters, flags, small `Copy` structs | `Vec`, `HashMap`, `String`, larger structs | Neither type is `Sync`: both are for state used from one thread at a time. ## The memoising calculator A calculator whose `fib(&self, n)` caches results needs two pieces of hidden state. The hit counter is a `u32`, a `Copy` value replaced whole, so `Cell<u32>` is the right home and `self.hits.update(|h| h + 1)` bumps it without any check. The cache is a `HashMap<u64, u64>`; inserting needs `&mut HashMap`, which a `Cell` will not lend, so it lives in a `RefCell` and the method calls `self.cache.borrow_mut().insert(n, v)`. ```rust struct Calculator { hits: Cell<u32>, cache: RefCell<HashMap<u64, u64>>, } ``` Note that the `Calculator` binding does not need `let mut`: interior mutability is exactly the ability to mutate through a shared path. ## Choosing 1. If you hold `&mut self` or own the value, use neither; ordinary mutation is checked at compile time. 2. If the state is `Copy` or cheap to swap whole, use `Cell<T>`: zero overhead and no panic path. 3. If you must call `&mut self` methods on the value in place, use `RefCell<T>` and keep each borrow short. 4. If the value is written once and then only read, a `OnceCell` (covered with lazy initialisation) fits better than either.

  • Can you store a `String` in a `Cell`, and what can you do with it?
    Yes. `Cell<String>` supports `set`, `replace`, `take` (because `String: Default`) and `into_inner`, but not `get`: rustc rejects `label.get()` with E0599, "the method `get` exists for struct `Cell<String>`, but its trait bounds were not satisfied", because `String` is not `Copy`. To edit it you `take()` the string, change it, and `set` it back.
  • Why is `Cell<T>` cheaper than `RefCell<T>`?
    `Cell<T>` is `#[repr(transparent)]` over `UnsafeCell<T>`, so it has the layout of `T` and no bookkeeping: soundness comes from never lending a reference. `RefCell<T>` stores an extra `isize` borrow counter beside the value and updates and checks it on every `borrow` and `borrow_mut`, plus the guard's drop.
  • When you hold `&mut` to the cell itself, do you still pay for the checks?
    No. Both `Cell::get_mut` and `RefCell::get_mut` take `&mut self` and return `&mut T` directly, with no runtime check, because the compiler has already proven exclusive access. `into_inner` likewise consumes the cell and hands back the value.

  • Cell only works with Copy types, so a String can never go in one.
  • Cell::get returns a reference to the value inside the cell.
  • RefCell borrow conflicts are reported by the compiler as E0502.
  • RefCell's borrow checks are compiled out of release builds.
  • A struct with a Cell field must be bound with let mut to change it.

Assumes Rust 1.99; Cell::update is stable since 1.88, and older code writes c.set(c.get() + 1) instead.

open as a page

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%

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.

open as a page

With Rust's `RefCell`, why does a method that calls `borrow_mut()` while iterating over `borrow()` compile, yet panic at run time?

level: middleimportance: must knowfreq 74%

basics

~20 s

RefCell moves the borrow rules to run time. The Ref from borrow() stays alive for the whole for loop, so borrow_mut() inside it finds a live shared borrow and panics with "RefCell already borrowed". Shorten the shared borrow, or use try_borrow_mut.

open as a page

Why are Rust's `Cell` and `RefCell` not `Sync`, and what does `UnsafeCell`, the type both are built on, provide?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Cell and RefCell mutate through &T with plain, non-atomic operations, so two threads sharing one could race on the value or RefCell's borrow counter; std therefore marks them !Sync. Both wrap UnsafeCell, the only legal way to mutate data behind a shared reference.

open as a page

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%

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.

open as a page