113. Arc::make_mut — Mutate Inside an Arc Without the Dance
You have an Arc<T>, you want a &mut T. Arc only hands out &T, so the usual workaround is clone-the-inner, mutate, rewrap. Arc::make_mut does that for you — and skips the clone when no one else is watching.
The manual version everyone writes once and then copies forever:
| |
It works, but it clones the Vec and reallocates the Arc every single time — even when this Arc is the only one pointing at the data.
Arc::make_mut takes &mut Arc<T> and hands you &mut T:
| |
One call, one borrow, and — crucially — no clone when this Arc is unique:
| |
When the Arc is shared, make_mut quietly clones the inner value into a fresh allocation and detaches your handle from the rest. The other handles keep seeing the old data — clone-on-write, exactly like you’d want:
| |
The same method exists on Rc for single-threaded code, with identical semantics. Reach for make_mut whenever you find yourself cloning the inside of an Arc just to change one field — you’ll skip the allocation in the common case and get an honest &mut T in return.