|
230 | 230 |
|
231 | 231 | #![stable(feature = "rust1", since = "1.0.0")]
|
232 | 232 |
|
233 |
| -use crate::fmt; |
234 | 233 | use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
|
235 | 234 | use crate::ops::{self, Deref, DerefMut};
|
| 235 | +use crate::{convert, fmt}; |
236 | 236 |
|
237 | 237 | /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
|
238 | 238 | ///
|
@@ -1214,6 +1214,38 @@ impl<T, E> Result<Option<T>, E> {
|
1214 | 1214 | }
|
1215 | 1215 | }
|
1216 | 1216 |
|
| 1217 | +impl<T, E> Result<Result<T, E>, E> { |
| 1218 | + /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>` |
| 1219 | + /// |
| 1220 | + /// # Examples |
| 1221 | + /// Basic usage: |
| 1222 | + /// ``` |
| 1223 | + /// #![feature(result_flattening)] |
| 1224 | + /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello")); |
| 1225 | + /// assert_eq!(Ok("hello"), x.flatten()); |
| 1226 | + /// |
| 1227 | + /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6)); |
| 1228 | + /// assert_eq!(Err(6), x.flatten()); |
| 1229 | + /// |
| 1230 | + /// let x: Result<Result<&'static str, u32>, u32> = Err(6); |
| 1231 | + /// assert_eq!(Err(6), x.flatten()); |
| 1232 | + /// ``` |
| 1233 | + /// |
| 1234 | + /// Flattening once only removes one level of nesting: |
| 1235 | + /// |
| 1236 | + /// ``` |
| 1237 | + /// #![feature(result_flattening)] |
| 1238 | + /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello"))); |
| 1239 | + /// assert_eq!(Ok(Ok("hello")), x.flatten()); |
| 1240 | + /// assert_eq!(Ok("hello"), x.flatten().flatten()); |
| 1241 | + /// ``` |
| 1242 | + #[inline] |
| 1243 | + #[unstable(feature = "result_flattening", issue = "70142")] |
| 1244 | + pub fn flatten(self) -> Result<T, E> { |
| 1245 | + self.and_then(convert::identity) |
| 1246 | + } |
| 1247 | +} |
| 1248 | + |
1217 | 1249 | // This is a separate function to reduce the code size of the methods
|
1218 | 1250 | #[inline(never)]
|
1219 | 1251 | #[cold]
|
|
0 commit comments