Skip to content

Commit e8f3a9f

Browse files
committed
add Result::map_or
1 parent e931f00 commit e8f3a9f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/libcore/result.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,28 @@ impl<T, E> Result<T, E> {
514514
}
515515
}
516516

517+
/// Applies a function to the contained value (if any),
518+
/// or returns the provided default (if not).
519+
///
520+
/// # Examples
521+
///
522+
/// ```
523+
/// #![feature(result_map_or)]
524+
/// let x: Result<_, &str> = Ok("foo");
525+
/// assert_eq!(x.map_or(42, |v| v.len()), 3);
526+
///
527+
/// let x: Result<&str, _> = Err("bar");
528+
/// assert_eq!(x.map_or(42, |v| v.len()), 42);
529+
/// ```
530+
#[inline]
531+
#[unstable(feature = "result_map_or", issue = "66293")]
532+
pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
533+
match self {
534+
Ok(t) => f(t),
535+
Err(_) => default,
536+
}
537+
}
538+
517539
/// Maps a `Result<T, E>` to `U` by applying a function to a
518540
/// contained [`Ok`] value, or a fallback function to a
519541
/// contained [`Err`] value.

0 commit comments

Comments
 (0)