Skip to content

Commit 64e8cfa

Browse files
authored
Rollup merge of rust-lang#66292 - lzutao:result-map_or, r=SimonSapin
add Result::map_or This PR adds this API to make it consistent with `Option::map_or`. ```rust impl<T, E> Result<T, E> { pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U { match self { Ok(t) => f(t), Err(_) => default, } } } ``` This API is very small. We already has a similar API for `Option::map_or`.
2 parents 53a83e7 + e8f3a9f commit 64e8cfa

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)