From e8f3a9ffbe0dc435d43767b31cc122ccc325f4c1 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Mon, 11 Nov 2019 13:25:19 +0000 Subject: [PATCH] add Result::map_or --- src/libcore/result.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index ed40a5f31d9bd..06c7041703ae5 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -514,6 +514,28 @@ impl Result { } } + /// Applies a function to the contained value (if any), + /// or returns the provided default (if not). + /// + /// # Examples + /// + /// ``` + /// #![feature(result_map_or)] + /// let x: Result<_, &str> = Ok("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Result<&str, _> = Err("bar"); + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + #[unstable(feature = "result_map_or", issue = "66293")] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Ok(t) => f(t), + Err(_) => default, + } + } + /// Maps a `Result` to `U` by applying a function to a /// contained [`Ok`] value, or a fallback function to a /// contained [`Err`] value.