Skip to content

Commit b8c6030

Browse files
committed
Implemented map_or_else for Result<T, E>
1 parent ec4a752 commit b8c6030

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/libcore/result.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,35 @@ impl<T, E> Result<T, E> {
470470
}
471471
}
472472

473+
/// Maps a `Result<T, E>` to `T` 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+
/// let k = 21;
489+
///
490+
/// let x = Ok("foo");
491+
/// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
492+
///
493+
/// let x = Err("bar");
494+
/// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
495+
/// ```
496+
#[inline]
497+
#[stable(feature = "rust1", since = "1.30.0")]
498+
pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
499+
self.map(map).unwrap_or_else(fallback)
500+
}
501+
473502
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
474503
/// contained [`Err`] value, leaving an [`Ok`] value untouched.
475504
///

0 commit comments

Comments
 (0)