RefCell<T>

RefCell<T> in Rust: The calibration bay has no lock on it. Anybody holding a works pass can walk up to the door, and the pass says nothing at all about what…

The Analogy: The Permit Board Outside The Calibration Bay

The calibration bay has no lock on it. Anybody holding a works pass can walk up to the door, and the pass says nothing at all about what they may do inside -- that was settled when the pass was printed, and it does not mention this bay. What governs the bay is a board on the wall beside the door, with two columns on it.

Two columns, because there are two kinds of job. Inspection permits go in the left-hand column and several can be open at once: four people reading the same gauge do not interfere with each other or with the gauge. A maintenance permit goes in the right-hand column, and it is only issued when both columns are otherwise empty, because somebody inside with a spanner changes what everyone else is reading.

The difference between this and a locked door is when you find out. A locked door and a key you were never issued is a fact about you, settled before you set off. The permit board tells you nothing until you are standing in front of it with your toolbag, and if the columns are not in the state you needed, you are turned away in the middle of the job. Nothing was wrong with your plan. Your plan simply was not checkable in advance.

And a permit has to be handed back. The board has no idea whether you are still inside; all it knows is what has been signed out and not returned. Put a permit in your pocket, wander off to another job, and the next person is refused for a reason nobody standing there can see -- the bay is empty and the board insists it is occupied. There is also a quieter way to use the board: rather than demanding a permit and being sent away, you can ask whether one would be issued, and plan around the answer.


Syntax or Core Structure

RefCell<T> lets you change a value through a shared reference. Look at what is missing from the first line:

use std::cell::RefCell;

fn main() {
    let readings = RefCell::new(vec![118, 124]);

    println!("start  {:?}", readings.borrow());

    readings.borrow_mut().push(131);
    readings.borrow_mut().push(107);

    println!("after  {:?}", readings.borrow());
    println!("len    {}", readings.borrow().len());

    {
        let mut w = readings.borrow_mut();

        w[0] = 999;
        w.sort();
    }

    println!("sorted {:?}", readings.borrow());

    let a = readings.borrow();
    let b = readings.borrow();

    println!("two readers {} {}", a.len(), b.len());
    println!("try_borrow_mut {}", readings.try_borrow_mut().is_err());
}

Output:

start  [118, 124]
after  [118, 124, 131, 107]
len    4
sorted [107, 124, 131, 999]
two readers 4 4
try_borrow_mut true

There is no mut on readings, and the vector inside it was pushed to, indexed into and sorted. That is what "interior mutability" names: the mutability is inside the value rather than in the binding.

borrow() returns a Ref<T> and borrow_mut() returns a RefMut<T>. Both are guards, both deref to the value, and both release when they drop -- which is the permit being handed back. The rule they enforce is exactly the rule the compiler enforces on & and &mut: any number of readers, or one writer, never both. The last two lines show both halves at once: two Refs coexist happily, and try_borrow_mut reports that a write would be refused while they live.

&T and &mut TRefCell<T>
The rule is checkedAt compile timeAt run time, on every borrow
The binding must be mut to writeYesNo
Breaking the rule gives youA compile errorA panic
Cost while runningNoneOne counter, read and written per borrow
Across threadsFineNot Sync, so no
What you hold ontoA referenceA guard that releases when dropped

Technical Depth: When The Board Turns You Away

The two panics, and the way to ask instead

use std::cell::RefCell;

fn main() {
    let log = RefCell::new(String::from("start"));

    let reader = log.borrow();

    println!("holding {reader}");
    println!("try_borrow_mut ok {}", log.try_borrow_mut().is_ok());

    drop(reader);

    log.borrow_mut().push_str("-more");

    println!("after {}", log.borrow());
}

Output:

holding start
try_borrow_mut ok false
after start-more

Replace that try_borrow_mut with a plain borrow_mut() and the program dies where it stands, with the message already borrowed: BorrowMutError. The mirror case -- calling borrow() while a RefMut is alive -- dies with already mutably borrowed: BorrowError. Both are panics, not errors, so nothing above them gets a chance to react; try_borrow and try_borrow_mut return Result and exist for the cases where a conflict is a situation rather than a bug.

The drop(reader) line is not decoration. Without it the guard would live to the end of main and the next borrow_mut() would panic. Guards are the whole difficulty of RefCell, and their lifetimes are decided by rules that are easy to get wrong.

Where a guard actually ends

use std::cell::RefCell;

fn add(cell: &RefCell<Vec<i32>>, n: i32) {
    cell.borrow_mut().push(n);
}

fn main() {
    let cell = RefCell::new(vec![10, 20]);

    let len = cell.borrow().len();

    add(&cell, len as i32);

    println!("statement scope {:?}", cell.borrow());

    let biggest = {
        let r = cell.borrow();

        *r.iter().max().unwrap_or(&0)
    };

    add(&cell, biggest);

    println!("block scope     {:?}", cell.borrow());

    let n = cell.borrow().len();

    match n {
        0 => println!("empty"),
        n => add(&cell, n as i32),
    }

    println!("read first      {:?}", cell.borrow());
}

Output:

statement scope [10, 20, 2]
block scope     [10, 20, 2, 20]
read first      [10, 20, 2, 20, 4]

Three shapes, all correct, and the third is the one to look at hardest. Written the natural way -- match cell.borrow().len() with an arm that calls add -- it panics, because the temporary in a match scrutinee is kept alive for the whole match expression, arms included. Hoisting the length into n first is not tidiness; it is the fix.

What makes this genuinely nasty is that if behaves differently. The condition of an if or a while is a terminating scope, so if cell.borrow().len() < 5 { add(&cell, 1); } releases the guard before the block and does not panic. if let follows the match rule rather than the if rule, because that is what it is. Two constructs that read almost identically, with opposite behaviour -- which is why the habit worth building is the one in the code above: finish the borrow, on its own line, before doing anything else.

The combination this module has been building towards

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

fn main() {
    let ledger = Rc::new(RefCell::new(Vec::new()));

    let gate_a = Rc::clone(&ledger);
    let gate_b = Rc::clone(&ledger);

    gate_a.borrow_mut().push("a-01");
    gate_b.borrow_mut().push("b-01");
    gate_a.borrow_mut().push("a-02");

    println!("handles {}", Rc::strong_count(&ledger));
    println!("entries {:?}", ledger.borrow());
    println!("count   {}", ledger.borrow().len());
}

Output:

handles 3
entries ["a-01", "b-01", "a-02"]
count   3

Neither type is sufficient alone. Rc gives many owners and hands out & only; RefCell gives mutation but has a single owner. Rc<RefCell<T>> gives both, and it is the standard shape for shared mutable state in single-threaded Rust -- gate_a and gate_b write to one vector and both see all three entries.

It is also the least checkable combination in this module, and worth reaching for deliberately rather than by habit. Rc makes reference cycles possible and RefCell makes runtime panics possible, so the pair gives up both of the guarantees the borrow checker was providing. Arc<Mutex<T>> is the same shape for threads, and it is the last lesson of this module.

The cheaper cousin

use std::cell::Cell;

fn main() {
    let hits = Cell::new(0u32);

    for _ in 0..5 {
        hits.set(hits.get() + 1);
    }

    println!("hits {}", hits.get());

    let old = hits.replace(100);

    println!("old {old}  now {}", hits.get());
}

Output:

hits 5
old 5  now 100

Cell<T> has no guards at all: it moves values in and out by copy, so there is nothing to hold and nothing to conflict, and it cannot panic. The price is that reading requires T: Copy, which rules out anything of interesting size.

Cell<T>RefCell<T>
Readingget(), which copies the value outborrow(), which lends it
RequiresT: Copy in order to read by valueNothing extra
Can panicNeverYes, on a conflicting borrow
Guards to keep track ofNoneYes, and their lifetimes are the difficulty
Right forCounters, flags, small Copy stateCollections, strings, anything large

Real World Example: A Price List That Remembers What It Worked Out

Every method here takes &self. Three fields change anyway.

use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::rc::Rc;

struct Tariffs {
    per_minute: u32,
    minimum: u32,
    cache: RefCell<BTreeMap<u32, u32>>,
    computed: Cell<u32>,
    served: Cell<u32>,
}

impl Tariffs {
    fn new(per_minute: u32, minimum: u32) -> Self {
        Tariffs {
            per_minute,
            minimum,
            cache: RefCell::new(BTreeMap::new()),
            computed: Cell::new(0),
            served: Cell::new(0),
        }
    }

    fn pence(&self, minutes: u32) -> u32 {
        self.served.set(self.served.get() + 1);

        let hit = self.cache.borrow().get(&minutes).copied();

        if let Some(found) = hit {
            return found;
        }

        let raw = minutes * self.per_minute;
        let charged = if raw < self.minimum { self.minimum } else { raw };

        self.computed.set(self.computed.get() + 1);
        self.cache.borrow_mut().insert(minutes, charged);

        charged
    }

    fn report(&self) -> String {
        let cache = self.cache.borrow();
        let keys: Vec<u32> = cache.keys().copied().collect();

        format!(
            "served {}  computed {}  cached {:?}",
            self.served.get(),
            self.computed.get(),
            keys
        )
    }
}

fn main() {
    let tariffs = Tariffs::new(6, 300);

    for minutes in [20, 90, 20, 15, 90, 20] {
        println!("{minutes:3} min  {:5}", tariffs.pence(minutes));
    }

    println!("{}", tariffs.report());

    let shared = Rc::new(tariffs);
    let desk = Rc::clone(&shared);

    println!("desk    {}", desk.pence(45));
    println!("counter {}", shared.pence(45));
    println!("{}", shared.report());
}

Output:

 20 min    300
 90 min    540
 20 min    300
 15 min    300
 90 min    540
 20 min    300
served 6  computed 3  cached [15, 20, 90]
desk    300
counter 300
served 8  computed 4  cached [15, 20, 45, 90]

Six calls, three pieces of arithmetic. pence promises its caller nothing will change, and what it actually promises is that nothing observable will change: the answer for a given number of minutes is identical whether it came out of the map or out of the multiplication. That gap between "does not mutate" and "does not mutate anything you can see" is the entire justification for interior mutability. The two counters are Cell because a u32 is Copy and a counter can never conflict with itself; the map is RefCell because a BTreeMap is not Copy and there is nothing to copy out.

The line let hit = self.cache.borrow().get(&minutes).copied(); is written that way on purpose. copied() turns the borrowed &u32 into a plain u32, so the guard dies at the semicolon and the borrow_mut() six lines later cannot possibly clash with it. Fold it into the if let -- if let Some(found) = self.cache.borrow().get(&minutes) -- and the guard is alive for the whole if let, which is harmless exactly until somebody adds an else branch that writes to the cache. Designing that shape out is cheaper than commenting on it.

The last three lines are why this is RefCell and not &mut. Two Rc handles to one Tariffs, both calling pence, and served climbing to 8 while computed stops at 4. Rc hands out & only, so a pence that took &mut self would not merely be inconvenient -- it would be uncallable through an Rc at all, and the cache could not exist. Rc<RefCell<Tariffs>> would also work and would be worse: it would make every reader of the price list contend with every other one, when in fact only the cache needs guarding. Putting the RefCell around the single field that changes is the version to reach for when the rest of the struct is fixed.

The limits are real. The borrow rules did not go away, they only moved to run time and got less polite: any future method that holds a Ref across a call to another method of this struct will panic in production, on the path nobody tested. None of this is thread-safe -- RefCell is not Sync, so Tariffs cannot cross a thread boundary at all, and swapping in the Mutex from the last lesson of this module is the fix rather than a tweak. The cache has no eviction, so a long-running process asked about a million distinct durations keeps a million entries for ever. And served and computed are observable state, so two identical calls genuinely return the same price but genuinely do not leave the object in the same condition -- which will matter to the first person who writes a test asserting on report().


Common Mistakes

  1. Holding a guard across a call. let g = cell.borrow(); then calling any function that also borrows the same cell. This is the archetypal RefCell panic, and it survives review easily because the two borrows are in different files.
  1. match cell.borrow().len() with an arm that writes. The scrutinee's temporary lives for the whole match, so the arm panics. Hoist the value into a let first. if let and while let have the same trap; a plain if does not, which is what makes it so easy to get wrong.
  1. try_borrow_mut().unwrap(). If you are going to unwrap it, borrow_mut() says the same thing more clearly. Use try_ only where you have an actual plan for the conflict.
  1. Using RefCell where &mut self would have compiled. You paid a counter, a guard and a possible panic in exchange for nothing. Reach for it when an Rc, a trait signature or an &self API has genuinely closed the other door.
  1. Treating RefCell as a way around the borrow checker. The rule is identical -- many readers or one writer. All that moved is when you find out and how badly it ends.
  1. RefCell<u32> for a counter. Cell<u32> does the same job with no guards and no way to panic. Reserve RefCell for values you cannot cheaply copy out.
  1. Assuming it is thread-safe. RefCell is Send but not Sync, so the compiler will stop you sharing one -- and the error will be about Sync on some enclosing type, several layers away from the RefCell that caused it.
  1. Rc<RefCell<T>> as the default architecture. It compiles for everything, which is exactly the problem: it turns ownership questions into runtime questions across the whole program.
  1. Storing a guard in a struct field or returning one from a function. Both are possible and both push the release point somewhere no reader will look for it. Return the copied or cloned value instead.

Best Practices

  • End every borrow on its own line. Copy, clone or compute the small thing you need, let the statement finish, then write.
  • Cell for Copy state, RefCell for everything else. A Cell cannot panic, so prefer it whenever the type allows.
  • Keep the borrowed region as small as it will go -- ideally a bare block containing one let and the expression that uses it.
  • Use try_borrow_mut only where a conflict is a legitimate state you can describe and handle, not as a panic you have moved one line down.
  • Wrap the smallest field that changes, not the whole struct. A RefCell around one cache is a local claim; a RefCell around the whole object is a claim about every field it has.
  • Prefer &mut self and ordinary fields until an Rc, a shared-reference API or a trait signature forces your hand. Interior mutability is a response to a constraint, not a starting position.
  • Write tests for the conflicting paths specifically. A RefCell panic is a logic bug, and unit tests are the only thing that will find it before your users do.
  • Say in a comment which methods borrow and for how long. It is the only documentation that will stop the next person nesting two of them.

Practice Exercises

  1. Trigger both panics on purpose: hold a Ref and call borrow_mut(), then hold a RefMut and call borrow(). Write down both messages, then fix each one with a drop and again with a block, and say which reads better.
  1. Write the version this lesson avoided -- match cell.borrow().len() with an arm that pushes -- and confirm it panics. Then change the match to an if with the same condition and confirm it does not. Explain the difference in one sentence.
  1. Swap the two Cell<u32> counters in Tariffs for RefCell<u32> and make it compile. Then list what you gained (nothing) and what you now have to think about (guards on every increment, and a panic that is newly possible).
  1. Add fn clear(&self) to Tariffs that empties the cache, and fn drain(&self) -> String that returns report() and then clears in one call. Make drain work without panicking, and say which line would have panicked in the obvious implementation.