83. Arc::unwrap_or_clone — Take Ownership Without the Dance
You need to own a T but all you have is an Arc<T>. The old pattern is a six-line fumble with try_unwrap. Arc::unwrap_or_clone collapses it into one call — and skips the clone entirely when it can.
The old dance
Arc::try_unwrap hands you the inner value — but only if you’re the last reference. Otherwise it gives your Arc back, and you have to clone.
| |
Every place that wanted an owned T from an Arc<T> wrote this same pattern, often subtly wrong.
The fix: unwrap_or_clone
Stabilized in Rust 1.76, Arc::unwrap_or_clone does exactly the right thing: move the inner value out if we’re the last owner, clone it otherwise.
| |
One call. No match. No deref gymnastics.
It actually skips the clone
The key win isn’t just ergonomics — it’s performance. When the refcount is 1, no clone happens; the T is moved out of the allocation directly.
| |
Also on Rc
The same method exists on Rc for single-threaded code — identical semantics, identical ergonomics:
| |
Anywhere you were reaching for try_unwrap().unwrap_or_else(|a| (*a).clone()), reach for unwrap_or_clone instead. Shorter, clearer, and it avoids the clone when it can.