Skip to content

Commit 65a0fb8

Browse files
authored
Rollup merge of rust-lang#45863 - LukasKalbertodt:add-option-filter, r=dtolnay
Add `Option::filter()` according to RFC 2124 (*old PR: rust-lang#44996) This is the implementation of [RFC "Add `Option::filter` to the standard library"](rust-lang/rfcs#2124). Tracking issue: rust-lang#45860 **Questions for code reviewers:** - Is the documentation sufficiently long? - Is the documentation easy enough to understand? - Is the position of the new method (after `and_then()`) a good one?
2 parents de083eb + e652144 commit 65a0fb8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/libcore/option.rs

+39
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,45 @@ impl<T> Option<T> {
607607
}
608608
}
609609

610+
/// Returns `None` if the option is `None`, otherwise calls `predicate`
611+
/// with the wrapped value and returns:
612+
///
613+
/// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
614+
/// value), and
615+
/// - `None` if `predicate` returns `false`.
616+
///
617+
/// This function works similar to `Iterator::filter()`. You can imagine
618+
/// the `Option<T>` being an iterator over one or zero elements. `filter()`
619+
/// lets you decide which elements to keep.
620+
///
621+
/// # Examples
622+
///
623+
/// ```rust
624+
/// #![feature(option_filter)]
625+
///
626+
/// fn is_even(n: &i32) -> bool {
627+
/// n % 2 == 0
628+
/// }
629+
///
630+
/// assert_eq!(None.filter(is_even), None);
631+
/// assert_eq!(Some(3).filter(is_even), None);
632+
/// assert_eq!(Some(4).filter(is_even), Some(4));
633+
/// ```
634+
#[inline]
635+
#[unstable(feature = "option_filter", issue = "45860")]
636+
pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
637+
match self {
638+
Some(x) => {
639+
if predicate(&x) {
640+
Some(x)
641+
} else {
642+
None
643+
}
644+
}
645+
None => None,
646+
}
647+
}
648+
610649
/// Returns the option if it contains a value, otherwise returns `optb`.
611650
///
612651
/// # Examples

0 commit comments

Comments
 (0)