Sub topic 13
Cell<T>: interior mutability for Copy values
This chapter assumes you know Rust ownership and borrowing, basic generics and traits, and the idea of interior mutability from the previous chapters. You should also know what Copy means: a type whose values are duplicated bit for bit on assignment, such as integers, bool, char, and tuples of those.
Where Cell fits
RefCell<T> lets you mutate through a shared reference by tracking borrows at runtime. That tracking has a cost: a counter to update, a possible panic, and a reference type (Ref or RefMut) to manage.
Cell<T> reaches the same goal with a different trick. It never gives you a reference to the inner value. You can only put a value in or take a value out. Since no reference to the contents ever exists, nothing can be invalidated, and no runtime borrow tracking is needed.
| Feature | `Cell<T>` | `RefCell<T>` |
|---|---|---|
| Hands out references to the contents | No | Yes (`Ref`, `RefMut`) |
| Runtime borrow counter | No | Yes |
| Can panic on misuse | No | Yes |
| Works with non-`Copy` types | Limited (via `take`, `replace`) | Yes |
| Typical use | Small flags and counters | Larger structures |
Basic use: get and set
Cell::new wraps a value. set replaces it. get returns a copy. The get method is only available when T: Copy.
use std::cell::Cell;
fn main() {
let counter = Cell::new(0);
counter.set(counter.get() + 1);
counter.set(counter.get() + 1);
println!("counter = {}", counter.get());
}The binding counter is not declared mut, and set takes &self. This program prints counter = 2.
A realistic case: a counter inside a shared struct
Cell is useful when one field of a struct needs to change while the rest of the struct is accessed through &self. A common example is counting how many times a method has been called.
use std::cell::Cell;
struct Lookup {
table: Vec<&'static str>,
hits: Cell<u32>,
}
impl Lookup {
fn new(table: Vec<&'static str>) -> Lookup {
Lookup { table, hits: Cell::new(0) }
}
fn get(&self, index: usize) -> Option<&str> {
self.hits.set(self.hits.get() + 1);
self.table.get(index).copied()
}
}
fn main() {
let lookup = Lookup::new(vec!["red", "green", "blue"]);
println!("{:?}", lookup.get(1));
println!("{:?}", lookup.get(7));
println!("{:?}", lookup.get(0));
println!("hits = {}", lookup.hits.get());
}The output is:
Some("green")
None
Some("red")
hits = 3The get method takes &self, so callers can hold many shared references to a Lookup and still record statistics. Without Cell, you would have to change the signature to &mut self, which would spread through every caller.
Why Cell is safe without borrow tracking
The danger in shared mutation is a reference that points to data that later changes or moves. For example, a &i32 into a value that another alias then overwrites.
Cell avoids the problem by construction:
getcopies the value out. The caller owns the copy, so later changes to the cell do not affect it.setmoves a new value in and drops the old one. No outstanding reference to the old value can exist, because the API never produced one.
The result is a compile-time guarantee with no runtime cost. Cell<T> has the same size and layout as T.
Working with non-Copy values
get requires Copy, but Cell is not limited to Copy types. Other methods move values rather than copying them:
replace(new)storesnewand returns the old value.take()returns the old value and leavesT::default()in its place. It needsT: Default.swap(&other)exchanges the contents of two cells.into_inner()consumes the cell and returns the value.
use std::cell::Cell;
fn main() {
let name = Cell::new(String::from("draft"));
let old = name.replace(String::from("final"));
println!("old = {old}");
let current = name.take();
println!("current = {current}");
let after = name.take();
println!("after = {:?}", after);
}The output is:
old = draft
current = final
after = ""Each call moves the whole String in or out, so no reference to it ever exists. For large structures, this pattern is awkward, and RefCell is usually a better fit.
Common errors
Calling get on a non-Copy type
use std::cell::Cell;
fn main() {
let c = Cell::new(String::from("hi"));
let s = c.get();
println!("{s}");
}This fails to compile. String is not Copy, so get does not exist for Cell<String>. The compiler reports that the method exists but its trait bounds were not satisfied. Use take or replace, or switch to RefCell<String>.
Expecting a reference to the contents
There is no borrow method on Cell. If you find yourself wanting &T out of a Cell<T>, that is the signal to use RefCell instead. A Cell works best for small, whole-value updates.
Read-modify-write over several steps
Each get or set is a single operation, but a sequence such as set(get() + 1) is not atomic with respect to other code. In single-threaded code, that is rarely a problem. A function called between the get and the set could change the value, though, and your update would overwrite its change.
use std::cell::Cell;
fn bump(c: &Cell<i32>) {
c.set(c.get() + 10);
}
fn main() {
let c = Cell::new(1);
let before = c.get();
bump(&c);
c.set(before + 1);
println!("c = {}", c.get());
}This prints c = 2, not 12. The stale before overwrote the effect of bump. Keep reads and writes close together, or use replace and take to make the exchange explicit.
Cell is not thread-safe
Cell<T> does not implement Sync, so you cannot share &Cell<T> across threads. The compiler rejects such code. For shared counters between threads, use atomic types such as AtomicUsize, or Mutex<T>, which a later chapter covers.
Choosing between Cell and RefCell
Use Cell when all of these hold:
- The value is small and cheap to copy, or you only need to swap whole values.
- You never need a reference into the value.
- You want zero runtime overhead and no possibility of a borrow panic.
Use RefCell when you need to call methods through a reference, to push onto a Vec, or to read a structure without copying it.
Exercise
A struct has a field calls: Cell<u32> and a method fn run(&self) that increments it. Why does this compile without &mut self, and why can't you add a method fn calls_ref(&self) -> &u32 that returns &self.calls contents directly?
Show answer
Cell::set takes &self, so it can change the value through a shared reference. This is safe because Cell never hands out references to its contents, so no alias can observe a half-changed or moved value. For the same reason, there is no safe way to get a &u32 from the cell. Offering one would reintroduce the aliasing problem that Cell avoids. Return self.calls.get() (a copy) instead, or use RefCell<u32> if you really need a reference guard.
Exercise
What does this program print, and why? use std::cell::Cell; fn main() { let a = Cell::new(String::from("x")); let b = Cell::new(String::from("y")); a.swap(&b); let taken = a.take(); println!("{:?} {:?}", taken, a.into_inner()); }
Show answer
It prints "y" "". After swap, a holds "y" and b holds "x". a.take() returns "y" and leaves an empty String (the default) in a. a.into_inner() then consumes the cell and returns that empty string.