Contents
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 | let mut x = 1; |
Interior mutability is the escape hatch. With Cell for example:
1 | let x = Cell::new(1); |
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 |
|
Sometimes you only want to tweak one field, or you do not want API surface that takes &mut self:
1 |
|
Cell is for Copy types only
For non-Copy types, Cell is a poor fit because get returns T and requires T: Copy:
1 | impl<T: Copy> Cell<T> { |
You can still store a non-Copy value in a Cell, but you lose the point of the API:
1 | let mut s = Cell::new(String::from("value")); |
RefCell exposes references
RefCell supports non-Copy types and hands you references instead of copied values.
1 | use std::cell::RefCell; |
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 |
|
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![]()
