diff --git a/src/libcore/result.rs b/src/libcore/result.rs index ac908342655b6..7443320e377ed 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -470,6 +470,36 @@ impl Result { } } + /// Maps a `Result` to `U` by applying a function to a + /// contained [`Ok`] value, or a fallback function to a + /// contained [`Err`] value. + /// + /// This function can be used to unpack a successful result + /// while handling an error. + /// + /// [`Ok`]: enum.Result.html#variant.Ok + /// [`Err`]: enum.Result.html#variant.Err + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(result_map_or_else)] + /// let k = 21; + /// + /// let x : Result<_, &str> = Ok("foo"); + /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); + /// + /// let x : Result<&str, _> = Err("bar"); + /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); + /// ``` + #[inline] + #[unstable(feature = "result_map_or_else", issue = "53268")] + pub fn map_or_else U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U { + self.map(map).unwrap_or_else(fallback) + } + /// Maps a `Result` to `Result` by applying a function to a /// contained [`Err`] value, leaving an [`Ok`] value untouched. ///