File tree 1 file changed +17
-0
lines changed
1 file changed +17
-0
lines changed Original file line number Diff line number Diff line change @@ -159,6 +159,15 @@ impl<T> Option<T> {
159
159
}
160
160
}
161
161
162
+ /// Filters an optional value using given function.
163
+ #[ inline( always) ]
164
+ pub fn filtered < ' a > ( self , f : & fn ( t : & ' a T ) -> bool ) -> Option < T > {
165
+ match self {
166
+ Some ( x) => if ( f ( & x) ) { Some ( x) } else { None } ,
167
+ None => None
168
+ }
169
+ }
170
+
162
171
/// Maps a `some` value from one type to another by reference
163
172
#[ inline( always) ]
164
173
pub fn map < ' a , U > ( & self , f : & fn ( & ' a T ) -> U ) -> Option < U > {
@@ -459,3 +468,11 @@ fn test_get_or_zero() {
459
468
let no_stuff: Option < int > = None ;
460
469
assert_eq ! ( no_stuff. get_or_zero( ) , 0 ) ;
461
470
}
471
+
472
+ #[ test]
473
+ fn test_filtered( ) {
474
+ let some_stuff = Some ( 42 ) ;
475
+ let modified_stuff = some_stuff. filtered( |& x| { x < 10 } ) ;
476
+ assert_eq ! ( some_stuff. get( ) , 42 ) ;
477
+ assert ! ( modified_stuff. is_none( ) ) ;
478
+ }
You can’t perform that action at this time.
0 commit comments