226. unwrap_or_default — Stop Spelling Out the Empty Value
Writing .unwrap_or(0) or .unwrap_or_else(String::new) to fall back to an empty value? If the type already has a Default, unwrap_or_default says it for you.
The fallback you keep typing out
You pull a value out of an Option, and the “missing” case is just the type’s natural zero: 0 for a number, "" for a string, [] for a vec. So you spell it out:
| |
Every one of those fallbacks is just Default::default(). unwrap_or_default reaches for it directly — no literal to pick, no closure to write:
| |
When Some, you get the value untouched; when None, you get T::default().
Where it shines: map lookups
Counting with a HashMap is the classic case — a missing key should read as zero:
| |
No .unwrap_or(0) sprinkled at every call site, and if the value type changes, the default follows along automatically.
It works on Result too
Result::unwrap_or_default discards the Err and hands back the default — handy when a parse failure should just mean “nothing”:
| |
And on your own types
Derive Default and the same trick works for your structs — the fallback stays in one place instead of scattered across the codebase:
| |
Reach for unwrap_or_default whenever the fallback is the empty value — let the type decide what empty means.