Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Option::filter() according to RFC 2124 #45863

Merged
merged 1 commit into from
Nov 10, 2017
Merged
Changes from all 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
39 changes: 39 additions & 0 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,45 @@ impl<T> Option<T> {
}
}

/// Returns `None` if the option is `None`, otherwise calls `predicate`
/// with the wrapped value and returns:
///
/// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
/// value), and
/// - `None` if `predicate` returns `false`.
///
/// This function works similar to `Iterator::filter()`. You can imagine
/// the `Option<T>` being an iterator over one or zero elements. `filter()`
/// lets you decide which elements to keep.
///
/// # Examples
///
/// ```rust
/// #![feature(option_filter)]
///
/// fn is_even(n: &i32) -> bool {
/// n % 2 == 0
/// }
///
/// assert_eq!(None.filter(is_even), None);
/// assert_eq!(Some(3).filter(is_even), None);
/// assert_eq!(Some(4).filter(is_even), Some(4));
/// ```
#[inline]
#[unstable(feature = "option_filter", issue = "45860")]
pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
match self {
Some(x) => {
if predicate(&x) {
Some(x)
} else {
None
}
}
None => None,
}
}

/// Returns the option if it contains a value, otherwise returns `optb`.
///
/// # Examples
Expand Down