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 ops::Try for Option { None } } + +impl Option> { + /// Converts from `Option>` to `Option` + /// + /// # Examples + /// Basic usage: + /// ``` + /// #![feature(option_flattening)] + /// let x: Option> = Some(Some(6)); + /// assert_eq!(Some(6), x.flatten()); + /// + /// let x: Option> = Some(None); + /// assert_eq!(None, x.flatten()); + /// + /// let x: Option> = None; + /// assert_eq!(None, x.flatten()); + /// ``` + /// Flattening once only removes one level of nesting: + /// ``` + /// #![feature(option_flattening)] + /// let x: Option>> = 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 { + self.and_then(convert::identity) + } +}