Skip to content

Commit

Permalink
Rollup merge of rust-lang#53777 - ivanbakel:result_map_or_else, r=ale…
Browse files Browse the repository at this point in the history
…xcrichton

Implemented map_or_else for Result<T, E>

Fulfills rust-lang#53268
The example is ripped from `Option::map_or_else`, with the types corrected.
  • Loading branch information
kennytm authored Sep 12, 2018
2 parents 605948f + 79408c3 commit 4f62077
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,36 @@ impl<T, E> Result<T, E> {
}
}

/// Maps a `Result<T, E>` 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, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
self.map(map).unwrap_or_else(fallback)
}

/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
/// contained [`Err`] value, leaving an [`Ok`] value untouched.
///
Expand Down

0 comments on commit 4f62077

Please sign in to comment.