diff --git a/src/libstd/option.rs b/src/libstd/option.rs index 80f4fb7643c80..894d29df5d719 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -159,6 +159,15 @@ impl Option { } } + /// Filters an optional value using given function. + #[inline(always)] + pub fn filtered<'a>(self, f: &fn(t: &'a T) -> bool) -> Option { + match self { + Some(x) => if(f(&x)) {Some(x)} else {None}, + None => None + } + } + /// Maps a `some` value from one type to another by reference #[inline(always)] pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option { @@ -459,3 +468,11 @@ fn test_get_or_zero() { let no_stuff: Option = None; assert_eq!(no_stuff.get_or_zero(), 0); } + +#[test] +fn test_filtered() { + let some_stuff = Some(42); + let modified_stuff = some_stuff.filtered(|&x| {x < 10}); + assert_eq!(some_stuff.get(), 42); + assert!(modified_stuff.is_none()); +} \ No newline at end of file