225. Option::map_or — Transform-or-Default in One Call, Skip the match
Reaching for a four-line match just to turn an Option into a plain value? map_or does the transform and the fallback in a single call.
The match you keep rewriting
You have an Option, you want a concrete value: apply a function if it’s Some, fall back to a default if it’s None.
| |
map_or(default, f) collapses both arms. The first argument is the None fallback, the second is what to do with the value inside Some:
| |
It beats the common .map(|n| n.len()).unwrap_or(0) too — same result, but no intermediate Option built just to immediately unwrap it.
The catch: the default is eager
map_or takes the default by value, so it’s computed whether or not you need it. With a cheap literal like 0 that’s free. With anything that allocates or does real work, you pay for it even on the Some path:
| |
When the fallback isn’t free, switch to map_or_else, which takes a closure and only calls it on None:
| |
It works on Result too
Result::map_or follows the same shape — the value goes through f, any Err yields the default:
| |
Use map_or when the default is a cheap literal, map_or_else when it isn’t, and let the match go.