Skip to content

Commit

Permalink
Rollup merge of rust-lang#60256 - ethanboxx:master, r=alexcrichton
Browse files Browse the repository at this point in the history
Option::flatten

This PR makes this possible.
```rust
assert_eq!(Some(6), Some(Some(6)).flatten());
assert_eq!(Some(6), Some(Some(6)).into());
```
  • Loading branch information
Centril authored Apr 29, 2019
2 parents eb3c530 + fa7ba66 commit bdf3a01
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}

0 comments on commit bdf3a01

Please sign in to comment.