54. Cell::update — Modify Interior Values Without the Gymnastics
Tired of writing cell.set(cell.get() + 1) every time you want to tweak a Cell value? Rust 1.88 added Cell::update — one call to read, transform, and write back.
The old way
Cell<T> gives you interior mutability for Copy types, but updating a value always felt clunky:
| |
You’re calling .get() and .set() in the same expression, which is repetitive and visually noisy — especially when the transformation is more complex than + 1.
Enter Cell::update
Stabilized in Rust 1.88, update takes a closure that receives the current value and returns the new one:
| |
One call. No repetition of the cell name. The intent — “increment this value” — is immediately clear.
Beyond simple increments
update shines when the transformation is more involved:
| |
Compare that to flags.set(flags.get() ^ 0b0000_0001) — the update version reads like a pipeline of transformations.
A practical example: tracking state in callbacks
Cell::update is especially handy inside closures where you need shared mutable state without reaching for RefCell:
| |
No RefCell, no runtime borrow checks, no panics — just a clean in-place update.
The signature
| |
Note the T: Copy bound — this works because Cell copies the value out, passes it to your closure, and copies the result back in. If you need this for non-Copy types, you’ll still want RefCell.
Simple, ergonomic, and long overdue. Available since Rust 1.88.0.