Skip to content

Commit 54a5a00

Browse files
committed
add tests, fix docs
1 parent 6b0a0af commit 54a5a00

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

library/core/src/option.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1965,8 +1965,23 @@ impl<T> Option<T> {
19651965
/// Reduces two options into one, using the provided function if both are `Some`.
19661966
///
19671967
/// 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.
1968+
/// Otherwise, if only one of `self` and `other` is `Some`, that one is returned.
1969+
/// If both `self` and `other` are `None`, `None` is returned.
1970+
///
1971+
/// # Examples
1972+
///
1973+
/// ```
1974+
/// #![feature(option_reduce)]
1975+
///
1976+
/// let x = Some(12);
1977+
/// let y = Some(17);
1978+
/// let z = None;
1979+
/// let f = |a, b| a + b;
1980+
///
1981+
/// assert_eq!(x.reduce(y, f), Some(29));
1982+
/// assert_eq!(x.reduce(z, f), Some(12));
1983+
/// assert_eq!(z.reduce(z, f), None);
1984+
/// ```
19701985
#[unstable(feature = "option_reduce", issue = "144273")]
19711986
pub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
19721987
where

library/coretests/tests/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
#![feature(never_type)]
7878
#![feature(next_index)]
7979
#![feature(numfmt)]
80+
#![feature(option_reduce)]
8081
#![feature(pattern)]
8182
#![feature(pointer_is_aligned_to)]
8283
#![feature(portable_simd)]

library/coretests/tests/option.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,3 +584,15 @@ fn as_slice() {
584584
assert_eq!(A, &[44]);
585585
assert_eq!(B, &[]);
586586
}
587+
588+
#[test]
589+
fn reduce_options() {
590+
let x = Some(10);
591+
let y = Some(7);
592+
let z = None::<i32>;
593+
594+
assert_eq!(x.reduce(y, |x, y| x + y), Some(17));
595+
assert_eq!(x.reduce(z, |x, y| x + y), Some(10));
596+
assert_eq!(y.reduce(z, |x, y| x + y), Some(7));
597+
assert_eq!(z.reduce(z, |x, y| x + y), None);
598+
}

0 commit comments

Comments
 (0)