]> git.proxmox.com Git - rustc.git/blobdiff - src/libcore/result.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / libcore / result.rs
index 0bc29e1bc662cfb94dc28f43b808d2d933401be6..c7b5777a16e7f7459c8d89f4f9b3b5a5f3d1f3ee 100644 (file)
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
-use crate::fmt;
 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
 use crate::ops::{self, Deref, DerefMut};
+use crate::{convert, fmt};
 
 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
 ///
@@ -521,14 +521,16 @@ impl<T, E> Result<T, E> {
         }
     }
 
-    /// Applies a function to the contained value (if any),
-    /// or returns the provided default (if not).
+    /// Applies a function to the contained value (if [`Ok`]),
+    /// or returns the provided default (if [`Err`]).
     ///
     /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
     /// the result of a function call, it is recommended to use [`map_or_else`],
     /// which is lazily evaluated.
     ///
     /// [`map_or_else`]: #method.map_or_else
+    /// [`Ok`]: enum.Result.html#variant.Ok
+    /// [`Err`]: enum.Result.html#variant.Err
     ///
     /// # Examples
     ///
@@ -1214,6 +1216,38 @@ impl<T, E> Result<Option<T>, E> {
     }
 }
 
+impl<T, E> Result<Result<T, E>, E> {
+    /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
+    ///
+    /// # Examples
+    /// Basic usage:
+    /// ```
+    /// #![feature(result_flattening)]
+    /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
+    /// assert_eq!(Ok("hello"), x.flatten());
+    ///
+    /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
+    /// assert_eq!(Err(6), x.flatten());
+    ///
+    /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
+    /// assert_eq!(Err(6), x.flatten());
+    /// ```
+    ///
+    /// Flattening once only removes one level of nesting:
+    ///
+    /// ```
+    /// #![feature(result_flattening)]
+    /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
+    /// assert_eq!(Ok(Ok("hello")), x.flatten());
+    /// assert_eq!(Ok("hello"), x.flatten().flatten());
+    /// ```
+    #[inline]
+    #[unstable(feature = "result_flattening", issue = "70142")]
+    pub fn flatten(self) -> Result<T, E> {
+        self.and_then(convert::identity)
+    }
+}
+
 // This is a separate function to reduce the code size of the methods
 #[inline(never)]
 #[cold]