Skip to content

Commit bdf3a01

Browse files
authored
Rollup merge of rust-lang#60256 - ethanboxx:master, r=alexcrichton
Option::flatten This PR makes this possible. ```rust assert_eq!(Some(6), Some(Some(6)).flatten()); assert_eq!(Some(6), Some(Some(6)).into()); ```
2 parents eb3c530 + fa7ba66 commit bdf3a01

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

src/libcore/option.rs

+31-1
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@
136136
#![stable(feature = "rust1", since = "1.0.0")]
137137

138138
use crate::iter::{FromIterator, FusedIterator, TrustedLen};
139-
use crate::{hint, mem, ops::{self, Deref}};
139+
use crate::{convert, hint, mem, ops::{self, Deref}};
140140
use crate::pin::Pin;
141141

142142
// Note that this is not a lang item per se, but it has a hidden dependency on
@@ -1413,3 +1413,33 @@ impl<T> ops::Try for Option<T> {
14131413
None
14141414
}
14151415
}
1416+
1417+
impl<T> Option<Option<T>> {
1418+
/// Converts from `Option<Option<T>>` to `Option<T>`
1419+
///
1420+
/// # Examples
1421+
/// Basic usage:
1422+
/// ```
1423+
/// #![feature(option_flattening)]
1424+
/// let x: Option<Option<u32>> = Some(Some(6));
1425+
/// assert_eq!(Some(6), x.flatten());
1426+
///
1427+
/// let x: Option<Option<u32>> = Some(None);
1428+
/// assert_eq!(None, x.flatten());
1429+
///
1430+
/// let x: Option<Option<u32>> = None;
1431+
/// assert_eq!(None, x.flatten());
1432+
/// ```
1433+
/// Flattening once only removes one level of nesting:
1434+
/// ```
1435+
/// #![feature(option_flattening)]
1436+
/// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1437+
/// assert_eq!(Some(Some(6)), x.flatten());
1438+
/// assert_eq!(Some(6), x.flatten().flatten());
1439+
/// ```
1440+
#[inline]
1441+
#[unstable(feature = "option_flattening", issue = "60258")]
1442+
pub fn flatten(self) -> Option<T> {
1443+
self.and_then(convert::identity)
1444+
}
1445+
}

0 commit comments

Comments
 (0)