From 6fe7867ea6f5f912346d75459499fca88f6ae563 Mon Sep 17 00:00:00 2001 From: Wim Looman Date: Thu, 19 Mar 2020 09:57:37 +0100 Subject: [PATCH] Add Result, E>::flatten -> Result --- src/libcore/result.rs | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 0bc29e1bc662c..0087b92f1f2d6 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -230,9 +230,9 @@ #![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`]). /// @@ -1214,6 +1214,38 @@ impl Result, E> { } } +impl Result, E> { + /// Converts from `Result, E>` to `Result` + /// + /// # Examples + /// Basic usage: + /// ``` + /// #![feature(result_flattening)] + /// let x: Result, u32> = Ok(Ok("hello")); + /// assert_eq!(Ok("hello"), x.flatten()); + /// + /// let x: Result, u32> = Ok(Err(6)); + /// assert_eq!(Err(6), x.flatten()); + /// + /// let x: Result, u32> = Err(6); + /// assert_eq!(Err(6), x.flatten()); + /// ``` + /// + /// Flattening once only removes one level of nesting: + /// + /// ``` + /// #![feature(result_flattening)] + /// let x: Result, 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 { + self.and_then(convert::identity) + } +} + // This is a separate function to reduce the code size of the methods #[inline(never)] #[cold]