Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/libcore/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
57 changes: 57 additions & 0 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,63 @@ impl<T> Option<T> {
pub fn replace(&mut self, value: T) -> Option<T> {
mem::replace(self, Some(value))
}

/// Zips `self` with another `Option`.
///
/// If `self` is `Some(s)` and other is `Some(o)`, this method returns `Some((s, o))`.
/// Otherwise, `None` is returned.
///
/// # Examples
///
/// ```
/// #![feature(option_zip)]
/// let x = Some(1);
/// let y = Some("hi");
/// let z = None::<u8>;
///
/// assert_eq!(x.zip(y), Some((1, "hi")));
/// assert_eq!(x.zip(z), None);
/// ```
#[unstable(feature = "option_zip", issue = "70086")]
pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
self.zip_with(other, |a, b| (a, b))
}

/// Zips `self` and another `Option` with function `f`.
///
/// If `self` is `Some(s)` and other is `Some(o)`, this method returns `Some(f(s, o))`.
/// Otherwise, `None` is returned.
///
/// # 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.5);
/// let y = Some(42.7);
///
/// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
/// assert_eq!(x.zip_with(None, Point::new), None);
/// ```
#[unstable(feature = "option_zip", issue = "70086")]
pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
where
F: FnOnce(T, U) -> R,
{
Some(f(self?, other?))
}
}

impl<T: Copy> Option<&T> {
Expand Down