diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 5a731766054..94fc2fd357a 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -140,6 +140,7 @@ #![feature(associated_type_bounds)] #![feature(const_type_id)] #![feature(const_caller_location)] +#![feature(option_zip)] #![feature(no_niche)] // rust-lang/rust#68303 #[prelude_import] diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 9b32442371c..5db92a1b352 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -913,6 +913,65 @@ impl Option { pub fn replace(&mut self, value: T) -> Option { mem::replace(self, Some(value)) } + + /// Zips `self` with another `Option`. + /// + /// Returns `Some((_, _))` when both `self` and `other` + /// are `Some(_)`, otherwise return `None`. + /// + /// # Examples + /// + /// ``` + /// #![feature(option_zip)] + /// let x = Some(1); + /// let y = Some("hi"); + /// let z = None::; + /// + /// assert_eq!(x.zip(y), Some((1, "hi"))); + /// assert_eq!(x.zip(z), None); + /// ``` + #[inline] + #[unstable(feature = "option_zip", issue = "none")] + pub fn zip(self, other: Option) -> Option<(T, U)> { + self.zip_with(other, |a, b| (a, b)) + } + + /// Zips `self` and another `Option` with function `f`. + /// + /// Returns `Some(_)` when both `self` and `other` + /// are `Some(_)`, otherwise return `None`. + /// + /// # Examples + /// + /// ``` + /// #![feature(option_zip)] + /// + /// #[derive(Debug, PartialEq)] + /// struct Point { + /// x: f64, + /// y: f64, + /// } + /// + /// impl Point { + /// fn new(x: f64, y: f64) -> Self { + /// Self { x, y } + /// } + /// } + /// + /// let x = Some(17.); + /// let y = Some(42.); + /// + /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17., y: 42. })); + /// assert_eq!(x.zip_with(None, Point::new), None); + /// ``` + #[inline] + #[unstable(feature = "option_zip", issue = "none")] + pub fn zip_with(self, other: Option, f: F) -> Option + where + F: FnOnce(T, U) -> R, + { + Some(f(self?, other?)) + } } impl Option<&T> {