Skip to content

Add Result<Result<T, E>, E>::flatten -> Result<T, E> #70140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`]).
///
Expand Down Expand Up @@ -1214,6 +1214,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>`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the documentation could be reworded a bit, to emphasize what happens if one of the results is an Err variant (which wasn't really needed for Option<T>::flatten). It should be noted that, in Rustdoc, you don't directly see the type of self when looking at the definition of a method.

///
/// # 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]
Expand Down