Sub topic 13
Cell<T>: interior mutability for Copy values
This chapter assumes you know RefCell<T> and the idea of interior mutability: changing a value through a shared reference (&T). Cell<T> is a smaller tool for the same job.
How Cell works
RefCell<T> hands out references to its contents and tracks them at runtime. Cell<T> never hands out a reference to what it holds. Instead it moves values in and out:
getreturns a copy of the value. It requiresT: Copy.setreplaces the value and drops the old one.replacestores a new value and returns the old one.takereturns the value and leavesDefault::default()behind. It requiresT: Default.
Because no reference to the inside ever exists, the borrow rules cannot be broken. There is no borrow counter and no panic. The check happens at compile time, and the cost at runtime is none.
A counter behind `&self`
The record method below takes &self, not &mut self. It can still update the counter.
use std::cell::Cell;
struct Counter {
hits: Cell<u32>,
}
impl Counter {
fn record(&self) {
self.hits.set(self.hits.get() + 1);
}
}
fn main() {
let counter = Counter { hits: Cell::new(0) };
counter.record();
counter.record();
println!("hits = {}", counter.hits.get());
}The program prints hits = 2. This pattern fits statistics, call counters, and flags on a value that many parts of a program hold by shared reference, for example through an Rc.
Cell compared with RefCell
| Row | `Cell<T>` | `RefCell<T>` |
|---|---|---|
| Access | Copies or moves values in and out | Returns `Ref` and `RefMut` guards |
| Element type | `get` needs `Copy` | Any type |
| Failure mode | None | Panics on a borrow violation |
| Runtime cost | None | Borrow flag check |
| Thread-safe | No | No |
Use Cell when the value is small and Copy, such as integers, booleans, or char. Use RefCell when you need to borrow into a larger value, such as a Vec or a String.
Non-Copy values
get is not available for a type that is not Copy. You can still use Cell by swapping values out.
use std::cell::Cell;
fn main() {
let name = Cell::new(String::from("old"));
let previous = name.replace(String::from("new"));
println!("previous = {previous}");
let current = name.take();
println!("current = {current}");
println!("after take = {:?}", name.into_inner());
}This prints previous = old, current = new, and after take = "". It works, but you cannot look at the contents without removing them. For anything beyond swapping, RefCell is usually clearer.
Common mistakes
- Reaching for
RefCell<i32>whenCell<i32>would do.RefCelladds a runtime check and a possible panic that you do not need. - Calling
geton aCellof a non-Copytype. The compiler reports that the method's trait bounds are not satisfied. - Expecting a reference into the cell. There is no
&mutaccess through a sharedCell, only whole-value operations.Cell::get_mutexists, but it needs&mut self, so it does not give interior mutability.
Exercise
A struct holds a Cell<Vec<i32>> and you call cell.get(). Why does this not compile, and how can you read the vector's length without cloning it?
Show answer
get requires T: Copy, and Vec<i32> is not Copy. You can take the vector, read its length, and set it back. A better choice is RefCell<Vec<i32>>, where borrow().len() reads the length without moving anything.