about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorLukas Kalbertodt <lukas.kalbertodt@gmail.com>2017-10-03 12:27:42 +0200
committerLukas Kalbertodt <lukas.kalbertodt@gmail.com>2017-11-08 10:23:12 +0100
commite65214441dd9b6ec4eff3821d988818ecb53abf6 (patch)
treea43b09c4cac76d339f17ddae9ad07ae9ed4c349b /src/libcore
parente177df3d5c4a5a9432f33f54ee459ea25bf7f2d2 (diff)
downloadrust-e65214441dd9b6ec4eff3821d988818ecb53abf6.tar.gz
rust-e65214441dd9b6ec4eff3821d988818ecb53abf6.zip
Add `Option::filter()` according to RFC 2124
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/option.rs39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs
index 980ea551f08..63c846b25ec 100644
--- a/src/libcore/option.rs
+++ b/src/libcore/option.rs
@@ -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