Skip to content

Commit 6b0a0af

Browse files
committed
add Option::reduce
1 parent 3f9f20f commit 6b0a0af

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

library/core/src/option.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1961,6 +1961,26 @@ impl<T> Option<T> {
19611961
_ => None,
19621962
}
19631963
}
1964+
1965+
/// Reduces two options into one, using the provided function if both are `Some`.
1966+
///
1967+
/// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1968+
/// Otherwise, if one of `self` and `other` is `Some`, that one is returned.
1969+
/// Otherwise, `None` is returned.
1970+
#[unstable(feature = "option_reduce", issue = "144273")]
1971+
pub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
1972+
where
1973+
T: Into<R>,
1974+
U: Into<R>,
1975+
F: FnOnce(T, U) -> R,
1976+
{
1977+
match (self, other) {
1978+
(Some(a), Some(b)) => Some(f(a, b)),
1979+
(Some(a), _) => Some(a.into()),
1980+
(_, Some(b)) => Some(b.into()),
1981+
_ => None,
1982+
}
1983+
}
19641984
}
19651985

19661986
impl<T, U> Option<(T, U)> {

0 commit comments

Comments
 (0)