]> git.lizzy.rs Git - rust.git/blobdiff - src/libcore/option.rs
Rollup merge of #47193 - cramertj:result-opts, r=TimNN
[rust.git] / src / libcore / option.rs
index d8f3ec38cf38c4a2297d592ab9b1d2c6c78652b5..b8fe28d0f0d71b6fa7a8c07084464754acb979d2 100644 (file)
@@ -407,9 +407,7 @@ pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
     }
 
     /// Applies a function to the contained value (if any),
-    /// or returns a [`default`][] (if not).
-    ///
-    /// [`default`]: ../default/trait.Default.html#tymethod.default
+    /// or returns the provided default (if not).
     ///
     /// # Examples
     ///
@@ -430,9 +428,7 @@ pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
     }
 
     /// Applies a function to the contained value (if any),
-    /// or computes a [`default`][] (if not).
-    ///
-    /// [`default`]: ../default/trait.Default.html#tymethod.default
+    /// or computes a default (if not).
     ///
     /// # Examples
     ///
@@ -850,7 +846,7 @@ impl<T: Default> Option<T> {
     /// Returns the contained value or a default
     ///
     /// Consumes the `self` argument then, if [`Some`], returns the contained
-    /// value, otherwise if [`None`], returns the default value for that
+    /// value, otherwise if [`None`], returns the [default value] for that
     /// type.
     ///
     /// # Examples
@@ -872,6 +868,7 @@ impl<T: Default> Option<T> {
     ///
     /// [`Some`]: #variant.Some
     /// [`None`]: #variant.None
+    /// [default value]: ../default/trait.Default.html#tymethod.default
     /// [`parse`]: ../../std/primitive.str.html#method.parse
     /// [`FromStr`]: ../../std/str/trait.FromStr.html
     #[inline]
@@ -884,6 +881,35 @@ pub fn unwrap_or_default(self) -> T {
     }
 }
 
+impl<T, E> Option<Result<T, E>> {
+    /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
+    ///
+    /// `None` will be mapped to `Ok(None)`.
+    /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(transpose_result)]
+    ///
+    /// #[derive(Debug, Eq, PartialEq)]
+    /// struct SomeErr;
+    ///
+    /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
+    /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
+    /// assert_eq!(x, y.transpose());
+    /// ```
+    #[inline]
+    #[unstable(feature = "transpose_result", issue = "47338")]
+    pub fn transpose(self) -> Result<Option<T>, E> {
+        match self {
+            Some(Ok(x)) => Ok(Some(x)),
+            Some(Err(e)) => Err(e),
+            None => Ok(None),
+        }
+    }
+}
+
 // This is a separate function to reduce the code size of .expect() itself.
 #[inline(never)]
 #[cold]