Skip to content
Closed
Changes from 1 commit
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
41 changes: 41 additions & 0 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,47 @@ impl<T> Option<T> {
{
Some(f(self?, other?))
}

/// Zips `self` and another `Option` with function `f`, or returns `self.or(other)`.
///
/// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
/// Otherwise, if `self` is `Some`, `self` is returned.
/// Otherwise, `other` is returned.
///
/// # Examples
///
/// ```
/// #![feature(option_or_zip_with)]
///
/// #[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!(Some(2).or_zip_with(Some(3), |a, b| a + b), Some(5));
/// assert_eq!(Some(2).or_zip_with(None, |a, b| a + b), Some(2));
/// assert_eq!(None.or_zip_with(Some(3), |a, b| a + b), Some(3));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These do not look like real use cases to me. At a first glance, you are trying to sum these up if any of them has a value, and get None when both of them do not. What does this achieve? You can either resolve this by responding to me or changing the example.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've altered the example to hopefully make the use-case clearly. Regardless, it is only an example. It's difficult to demonstrate a real use-case in such a limited, controlled environment.

/// ```
#[unstable(feature = "option_or_zip_with", issue = "70086")]
pub fn or_zip_with<F>(self, other: Option<T>, f: F) -> Option<T>
where
F: FnOnce(T, T) -> T,
{
match (self, other) {
(Some(a), Some(b)) => Some(f(a, b)),
(a, b) => a.or(b),
}
}
}

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