Skip to content

Commit

Permalink
Rollup merge of rust-lang#45863 - LukasKalbertodt:add-option-filter, …
Browse files Browse the repository at this point in the history
…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?
  • Loading branch information
kennytm authored Nov 10, 2017
2 parents de083eb + e652144 commit 65a0fb8
Showing 1 changed file with 39 additions and 0 deletions.
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

0 comments on commit 65a0fb8

Please sign in to comment.