diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 1d264b260767e..675556b07a838 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -1253,6 +1253,36 @@ impl Option { } } + /// Maps an `Option` to a `U` by applying function `f` to the contained + /// value if the option is [`Some`], otherwise if [`None`], returns the + /// [default value] for the type `U`. + /// + /// # Examples + /// + /// ``` + /// #![feature(result_option_map_or_default)] + /// + /// let x: Option<&str> = Some("hi"); + /// let y: Option<&str> = None; + /// + /// assert_eq!(x.map_or_default(|x| x.len()), 2); + /// assert_eq!(y.map_or_default(|y| y.len()), 0); + /// ``` + /// + /// [default value]: Default::default + #[inline] + #[unstable(feature = "result_option_map_or_default", issue = "138099")] + pub fn map_or_default(self, f: F) -> U + where + U: Default, + F: FnOnce(T) -> U, + { + match self { + Some(t) => f(t), + None => U::default(), + } + } + /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to /// [`Ok(v)`] and [`None`] to [`Err(err)`]. /// diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 736ffb7d0caf3..ef2da5e8fbf41 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -858,6 +858,36 @@ impl Result { } } + /// Maps a `Result` to a `U` by applying function `f` to the contained + /// value if the result is [`Ok`], otherwise if [`Err`], returns the + /// [default value] for the type `U`. + /// + /// # Examples + /// + /// ``` + /// #![feature(result_option_map_or_default)] + /// + /// let x: Result<_, &str> = Ok("foo"); + /// let y: Result<&str, _> = Err("bar"); + /// + /// assert_eq!(x.map_or_default(|x| x.len()), 3); + /// assert_eq!(y.map_or_default(|y| y.len()), 0); + /// ``` + /// + /// [default value]: Default::default + #[inline] + #[unstable(feature = "result_option_map_or_default", issue = "138099")] + pub fn map_or_default(self, f: F) -> U + where + U: Default, + F: FnOnce(T) -> U, + { + match self { + Ok(t) => f(t), + Err(_) => U::default(), + } + } + /// Maps a `Result` to `Result` by applying a function to a /// contained [`Err`] value, leaving an [`Ok`] value untouched. ///