summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorLzu Tao <taolzu@gmail.com>2019-11-11 13:25:19 +0000
committerLzu Tao <taolzu@gmail.com>2019-11-12 03:22:04 +0000
commite8f3a9ffbe0dc435d43767b31cc122ccc325f4c1 (patch)
tree2a459e2bfc8dfe1566b12a37fddc7d78f6600054 /src/libcore
parente931f00f658b59481925deb0152503038ca69b9e (diff)
downloadrust-e8f3a9ffbe0dc435d43767b31cc122ccc325f4c1.tar.gz
rust-e8f3a9ffbe0dc435d43767b31cc122ccc325f4c1.zip
add Result::map_or
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/result.rs22
1 files changed, 22 insertions, 0 deletions
diff --git a/src/libcore/result.rs b/src/libcore/result.rs
index ed40a5f31d9..06c7041703a 100644
--- a/src/libcore/result.rs
+++ b/src/libcore/result.rs
@@ -514,6 +514,28 @@ impl<T, E> Result<T, E> {
         }
     }
 
+    /// 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, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
+        match self {
+            Ok(t) => f(t),
+            Err(_) => default,
+        }
+    }
+
     /// Maps a `Result<T, E>` to `U` by applying a function to a
     /// contained [`Ok`] value, or a fallback function to a
     /// contained [`Err`] value.