Skip to content

Commit 4f62077

Browse files
authored
Rollup merge of rust-lang#53777 - ivanbakel:result_map_or_else, r=alexcrichton
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.
2 parents 605948f + 79408c3 commit 4f62077

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/libcore/result.rs

+30
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,36 @@ impl<T, E> Result<T, E> {
470470
}
471471
}
472472

473+
/// Maps a `Result<T, E>` to `U` by applying a function to a
474+
/// contained [`Ok`] value, or a fallback function to a
475+
/// contained [`Err`] value.
476+
///
477+
/// This function can be used to unpack a successful result
478+
/// while handling an error.
479+
///
480+
/// [`Ok`]: enum.Result.html#variant.Ok
481+
/// [`Err`]: enum.Result.html#variant.Err
482+
///
483+
/// # Examples
484+
///
485+
/// Basic usage:
486+
///
487+
/// ```
488+
/// #![feature(result_map_or_else)]
489+
/// let k = 21;
490+
///
491+
/// let x : Result<_, &str> = Ok("foo");
492+
/// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
493+
///
494+
/// let x : Result<&str, _> = Err("bar");
495+
/// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
496+
/// ```
497+
#[inline]
498+
#[unstable(feature = "result_map_or_else", issue = "53268")]
499+
pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
500+
self.map(map).unwrap_or_else(fallback)
501+
}
502+
473503
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
474504
/// contained [`Err`] value, leaving an [`Ok`] value untouched.
475505
///

0 commit comments

Comments
 (0)