diff options
| author | Mazdak Farrokhzad <twingoow@gmail.com> | 2019-04-29 22:22:36 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-04-29 22:22:36 +0200 |
| commit | bdf3a0106585a1c150def0c5ec3dad1f1b791baa (patch) | |
| tree | 330a99ab46d6de4234585798f96612ba9a7de0da /src/libcore | |
| parent | eb3c53071a8e403ea98292f99f520439473ed409 (diff) | |
| parent | fa7ba66e6a1799982b200d563006d3c6d390aefe (diff) | |
| download | rust-bdf3a0106585a1c150def0c5ec3dad1f1b791baa.tar.gz rust-bdf3a0106585a1c150def0c5ec3dad1f1b791baa.zip | |
Rollup merge of #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()); ```
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/option.rs | 32 |
1 files changed, 31 insertions, 1 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 9599491462e..6b7f491effb 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -136,7 +136,7 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::iter::{FromIterator, FusedIterator, TrustedLen}; -use crate::{hint, mem, ops::{self, Deref}}; +use crate::{convert, hint, mem, ops::{self, Deref}}; use crate::pin::Pin; // 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> { None } } + +impl<T> Option<Option<T>> { + /// Converts from `Option<Option<T>>` to `Option<T>` + /// + /// # Examples + /// Basic usage: + /// ``` + /// #![feature(option_flattening)] + /// let x: Option<Option<u32>> = Some(Some(6)); + /// assert_eq!(Some(6), x.flatten()); + /// + /// let x: Option<Option<u32>> = Some(None); + /// assert_eq!(None, x.flatten()); + /// + /// let x: Option<Option<u32>> = None; + /// assert_eq!(None, x.flatten()); + /// ``` + /// Flattening once only removes one level of nesting: + /// ``` + /// #![feature(option_flattening)] + /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6))); + /// assert_eq!(Some(Some(6)), x.flatten()); + /// assert_eq!(Some(6), x.flatten().flatten()); + /// ``` + #[inline] + #[unstable(feature = "option_flattening", issue = "60258")] + pub fn flatten(self) -> Option<T> { + self.and_then(convert::identity) + } +} |
