File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -607,6 +607,45 @@ impl<T> Option<T> {
607
607
}
608
608
}
609
609
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
+
610
649
/// Returns the option if it contains a value, otherwise returns `optb`.
611
650
///
612
651
/// # Examples
You can’t perform that action at this time.
0 commit comments