Rust interior mutability — Cell and RefCell

Contents

  1. 1. Why interior mutability?
    1. 1.1. Mutating a struct field
  2. 2. Cell is for Copy types only
  3. 3. RefCell exposes references
  4. 4. Runtime checks

Interior mutability means a value looks immutable from the outside but can still be changed on the inside. It shows up when you hold an immutable reference and still need to update the data.

Cell and RefCell are Rust’s two main options. Cell targets Copy types; RefCell handles non-Copy types.

When do you actually reach for them, and why two types? Below are a few concrete situations.

Why interior mutability?

If you need two mutable references at once, you hit the usual borrow rule: only one &mut at a time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
let mut x = 1;
let y = &mut x;
let z = &mut x;
x = 2;
*y = 3;
*z = 4;
println!("{}", x);
# will get error:
# error[E0499]: cannot borrow `x` as mutable more than once at a time
# --> src/main.rs:5:9
# |
# 4 | let y = &mut x;
# | ------ first mutable borrow occurs here
# 5 | let z = &mut x;
# | ^^^^^^ second mutable borrow occurs here
# 6 | x = 2;
# 7 | *y = 3;
# | ------ first borrow later used here

# error[E0506]: cannot assign to `x` because it is borrowed
# --> src/main.rs:6:1
# |
# 4 | let y = &mut x;
# | ------ `x` is borrowed here
# 5 | let z = &mut x;
# 6 | x = 2;
# | ^^^^^ `x` is assigned to here but it was already borrowed
# 7 | *y = 3;
# | ------ borrow later used here

Interior mutability is the escape hatch. With Cell for example:

1
2
3
4
5
6
7
let x = Cell::new(1);
let y = &x;
let z = &x;
x.set(2);
y.set(3);
z.set(4);
println!("{}", x.get());

Cell wraps get and set so you can change the value without marking the binding mut.

Mutating a struct field

Normally you need mut on the struct and &mut self on the method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#[derive(Debug, Default)]
struct Person {
age: u32,
name: String,
}

impl Person {
fn celebrate_birthday(&mut self) {
let current_age = self.age;
self.age = current_age + 1;
}
}
let mut person = Person::default();
person.celebrate_birthday();
println!("Age after birthday: {}", person.age);

Sometimes you only want to tweak one field, or you do not want API surface that takes &mut self:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#[derive(Debug, Default)]
struct Person {
age: Cell<u32>,
name: String,
}

impl Person {
// Receiver does not need to be `mut`
fn celebrate_birthday(&self) {
let current_age = self.age.get();
self.age.set(current_age + 1);
}
}
person.celebrate_birthday();
println!("Age after birthday: {}", person.age.get());

Cell is for Copy types only

For non-Copy types, Cell is a poor fit because get returns T and requires T: Copy:

1
2
impl<T: Copy> Cell<T> {
pub fn get(&self) -> T {

You can still store a non-Copy value in a Cell, but you lose the point of the API:

1
2
3
4
5
let mut s = Cell::new(String::from("value"));
// No `s.get()` — `String` is not `Copy`
// `get_mut()` needs the Cell itself to be mutable, which defeats the pattern
*s.get_mut() = String::from("value2");
println!("{}", s.into_inner());

RefCell exposes references

RefCell supports non-Copy types and hands you references instead of copied values.

1
2
3
4
5
6
7
use std::cell::RefCell;

let c = RefCell::new("hello".to_owned());
*c.borrow_mut() = "bonjour".to_owned();
let val = c.borrow();

assert_eq!(&*val, "bonjour");

Runtime checks

Swap the order — borrow first, then mutably borrow — and it compiles but panics at runtime.

RefCell still enforces borrowing rules; it just checks them when the code runs. Violations panic.

1
2
3
4
5
6
7
8
9
10
11
12

```rust
use std::cell::RefCell;

let c = RefCell::new("hello".to_owned());
let val = c.borrow(); // borrow first, then mutate, then use `val`
*c.borrow_mut() = "bonjour".to_owned();

assert_eq!(&*val, "bonjour");

# will panic:
# thread 'main' panicked at 'already borrowed: BorrowMutError', src/main.rs:7:8

So: Cell is the lightweight choice for small Copy data when you want interior mutability as values. RefCell is for shared interior mutability through references when the type is not Copy.

Questions? Leave a comment below or email: newbvirgil@gmail.com