From e65214441dd9b6ec4eff3821d988818ecb53abf6 Mon Sep 17 00:00:00 2001 From: Lukas Kalbertodt Date: Tue, 3 Oct 2017 12:27:42 +0200 Subject: [PATCH] Add `Option::filter()` according to RFC 2124 --- src/libcore/option.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 980ea551f0806..63c846b25eca5 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -607,6 +607,45 @@ impl Option { } } + /// 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` 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 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