Skip to content

Commit f3966e4

Browse files
committed
Added filtered method for Option type
1 parent d1927d2 commit f3966e4

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/libstd/option.rs

+17
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,15 @@ impl<T> Option<T> {
159159
}
160160
}
161161

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+
162171
/// Maps a `some` value from one type to another by reference
163172
#[inline(always)]
164173
pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
@@ -459,3 +468,11 @@ fn test_get_or_zero() {
459468
let no_stuff: Option<int> = None;
460469
assert_eq!(no_stuff.get_or_zero(), 0);
461470
}
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+
}

0 commit comments

Comments
 (0)