Add `Option::map_or_default`

Option has unwrap, unwrap_or, unwrap_or_else and unwrap_or_default. It similarly has map, map_or, map_or_else and map_or_default. Oops, that one is missing. I propose we add it:

impl<T> Option<T> {
    pub fn map_or_default<U: Default, F: FnOnce(T) -> U>(self, f: F) -> U {
        match self {
            Some(t) => f(t),
            None => Default::default(),
        }
    }
}
4 Likes

For something as small as this I think that just making a PR to add the feature in an unstable form is good enough.

1 Like

What do you mean by "in an unstable form"?

I mean that the function is marked as unstable with a tracking issue.

With standalone default (once that’s stabilized) the alternative of writing .map_or_else(default, |x| { … }) isn’t really more overhead.

3 Likes

Indeed I’d say that unwrap_or_default will become rather redundant once you can write unwrap_or(default()) or unwrap_or_else(default).

By the way, in case you guys aren’t aware, one can already write Default::default as <_>::default which is only “slightly” longer that default. So .unwrap_or_else(<_>::default) or .map_or_else(<_>::default, |x| { … })

1 Like

Feel free to voice any concerns (or support) you have in the RFC pull request I posted: RFC: map_or_default in Option and Result by orlp · Pull Request #3148 · rust-lang/rfcs · GitHub.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.