skip to content

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%

answer

  1. the compiler sees only &self
  2. a live Ref keeps the counter up
  3. the guard lives to the loop's end
  4. try_borrow_mut returns Err(BorrowMutError)
  5. copy out, drop, then mutate

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.

solid answer

~40 s

To the compiler, `self.cache.borrow()` and `self.cache.borrow_mut()` are two calls that each take `&self` and return a guard, so there is no E0502 to report. The check happens inside the cell: `borrow()` raises a counter, and `borrow_mut()` succeeds only when that counter is zero. In `for (&n, &v) in self.cache.borrow().iter()`, the iterator borrows from the temporary `Ref`, so the `Ref` lives until the loop ends, and the `borrow_mut()` in the body panics with `RefCell already borrowed`. This check runs in every build profile. The fixes are to copy what you need into a local `Vec`, let the `Ref` drop, then take one `RefMut`; to restructure so a single `borrow_mut()` does the whole job; or, when a clash is expected and recoverable, to call `try_borrow_mut()`, which returns `Err(BorrowMutError)` instead of panicking.

code

rust · 22 lines
rust
use std::cell::RefCell;
use std::collections::HashMap;

struct Calculator {
    cache: RefCell<HashMap<u64, u64>>,
}

impl Calculator {
    // Pre-compute the double of every cached input.
    fn warm_doubles(&self) {
        for (&n, &v) in self.cache.borrow().iter() {
            // A Ref from borrow() is still alive here.
            self.cache.borrow_mut().insert(n * 2, v * 2);
        }
    }
}

fn main() {
    let calc = Calculator { cache: RefCell::new(HashMap::from([(3, 9)])) };
    calc.warm_doubles();
    println!("{}", calc.cache.borrow().len());
}

go deeper

for a junior

Recall that RefCell compiles code the borrow checker would reject and enforces the same rule at run time, panicking with RefCell already borrowed.

for a middle

Explain the counter: Ref guards raise it, borrow_mut needs zero, and a temporary Ref in a for or match head lives for the whole loop or match.

for a senior

Diagnose from the panic location backwards to the guard still alive, and fix by copying out or using one guard rather than sprinkling try_borrow_mut.

for a principal

Treat each RefCell as a deferred compile error: require short, local borrows and no guard held across callbacks, so a panic in production stays unlikely.

## What the compiler checks, and what it leaves to run time Rust's borrow checker enforces **aliasing XOR mutation** on references at compile time. `RefCell<T>` keeps the same rule but enforces it **dynamically**. Its two methods have these signatures: - `borrow(&self) -> Ref<'_, T>` - `borrow_mut(&self) -> RefMut<'_, T>` Both take a **shared** `&self`. From the compiler's point of view, a method that calls both is just taking two shared borrows of the `RefCell` field, which is always allowed. So code that would be rejected with E0502 if written with plain references compiles happily once the data sits in a `RefCell`. The conflict has not gone away; it has moved to run time, where it becomes a panic. ## The borrow counter inside the cell A `RefCell` stores the value in an `UnsafeCell` plus a counter, a `Cell<isize>`: - **Zero** means no borrow is active. - **Positive** values count the live `Ref` guards; any number of them may coexist. - **Negative** values mean a `RefMut` is live. `borrow()` fails if a writer is active; `borrow_mut()` fails if the counter is anything but zero. Dropping a guard gives its share back. There is no `cfg(debug_assertions)` around this logic in `core/src/cell.rs`: the check runs in release builds too. ## Why the guard outlives the line you thought The trap is often not two adjacent `let` statements; it is a **temporary** guard living longer than it looks: 1. In `for (&n, &v) in self.cache.borrow().iter()`, the iterator borrows from the temporary `Ref`, so the `Ref` lives for the entire loop. 2. In `match self.cache.borrow().get(&k) { ... }`, the scrutinee's temporaries live until the end of the `match`, so a `borrow_mut()` in any arm panics, including on the 2024 edition. 3. A `Ref` or `RefMut` stored in a `let` binding lives to the end of its block unless you call `drop(guard)`. 4. A guard held while calling a callback or another method causes a panic if that code borrows the same cell again in a conflicting way. The 2024 edition (stable since Rust 1.85) shortened one of these: in `if let ... else`, the scrutinee's temporaries are now dropped **before** the `else` branch runs, so a lookup-or-insert written as `if let Some(v) = cache.borrow().get(&k) { .. } else { cache.borrow_mut().insert(k, ..); }` panics on the 2021 edition and works on 2024. That rule belongs to the material on the 2024 edition; for `RefCell` code the lesson is that the same shape written as `match` still panics. ## The two panics and their non-panicking forms | Call | Fails when | Panic message | Non-panicking form | |---|---|---|---| | `borrow()` | a `RefMut` is live | `RefCell already mutably borrowed` | `try_borrow()` returns `Err(BorrowError)` | | `borrow_mut()` | any `Ref` or `RefMut` is live | `RefCell already borrowed` | `try_borrow_mut()` returns `Err(BorrowMutError)` | The panic location reported is the call that failed, not the earlier borrow still holding the cell, so a backtrace (`RUST_BACKTRACE=1`) and a read of the guards alive at that point are how you find the culprit. ## Fixing it 1. **Copy out, then mutate.** Collect the keys or values you need into a local `Vec`, let the `Ref` drop at the end of that statement, then take one `RefMut` for the writes. 2. **One guard for the whole job.** If the method both reads and writes, take a single `borrow_mut()` at the top and do everything through it. 3. **Scope the guard.** Put the borrow in an inner block or call `drop(guard)` before re-borrowing. 4. **Use `try_borrow_mut()` only for legitimate re-entrance**, such as a callback that may fire while its caller holds the cell; matching on the `Err` lets you skip or defer the write. Using it to hide a borrow that always overlaps turns a loud bug into a silent one. ```rust let pairs: Vec<(u64, u64)> = self.cache.borrow().iter().map(|(&n, &v)| (n, v)).collect(); let mut cache = self.cache.borrow_mut(); for (n, v) in pairs { cache.insert(n * 2, v * 2); } ``` Here the `Ref` is a temporary of the first statement and is gone before `borrow_mut()` runs.

  • Did the 2024 edition change when a `RefCell` guard in an `if let` is dropped?
    Yes, for `if let` with an `else`. Since the 2024 edition (Rust 1.85) the scrutinee's temporaries are dropped before the `else` branch, so `if let Some(v) = c.borrow().get(&k) { .. } else { c.borrow_mut().insert(k, 0); }` panics on 2021 and works on 2024. A `match` on the same expression still keeps the `Ref` alive through every arm and still panics.
  • When is `try_borrow_mut` the right tool rather than a cover for a bug?
    When re-entrance is part of the design: an observer callback that can fire while its caller already holds the cell, or a logger that must never panic. Matching on `Err(BorrowMutError)` lets that path skip or queue the write. If the borrows always overlap, the code is wrong and should be restructured; `try_borrow_mut` would only hide it.
  • Do two `borrow()` calls on the same `RefCell` conflict?
    No. Any number of `Ref` guards may coexist; each raises the positive counter and gives its share back on drop. Only a `borrow_mut()` while any guard is live, or a `borrow()` while a `RefMut` is live, panics.

A RefCell is like a meeting room whose door sheet is checked the moment you walk in, not when you book: any number of people may sit in to listen, but someone who wants to rearrange the furniture must find the room empty, and if it is not, the attempt fails on the spot instead of waiting in the corridor.

  • The borrow checker rejects this method with E0502 at compile time.
  • RefCell checks only run in debug builds, so release builds just race.
  • borrow_mut waits until the other borrow is released, like a lock.
  • Two simultaneous borrow calls on one RefCell also panic.
  • try_borrow_mut avoids the conflict by handing back a clone of the value.

Assumes Rust 1.99 on the 2024 edition (stable since 1.85), whose if let scope drops scrutinee temporaries before the else branch; the RefCell panic rules themselves date from Rust 1.0.