Skip to content

Commit ac4211e

Browse files
committed
auto merge of #7279 : hanny24/rust/master, r=msullivan
This commit adds filtered method for Option type. It is not exactly necessary (chain method can be used instead), however I believe that this approach using extra filtered method is more convinient.
2 parents f827561 + f3966e4 commit ac4211e

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]
164173
pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
@@ -464,3 +473,11 @@ fn test_get_or_zero() {
464473
let no_stuff: Option<int> = None;
465474
assert_eq!(no_stuff.get_or_zero(), 0);
466475
}
476+
477+
#[test]
478+
fn test_filtered() {
479+
let some_stuff = Some(42);
480+
let modified_stuff = some_stuff.filtered(|&x| {x < 10});
481+
assert_eq!(some_stuff.get(), 42);
482+
assert!(modified_stuff.is_none());
483+
}

0 commit comments

Comments
 (0)