Trait IteratorOptionalFilterExt

Source
pub trait IteratorOptionalFilterExt<P: FnMut(&Self::Item) -> bool>: Iterator + Sized {
    // Provided method
    fn optional_filter(self, predicate: Option<P>) -> OptionalFilter<Self, P>  { ... }
}
Expand description

Extension trait for adding the optional_filter method to iterators.

Provided Methods§

Source

fn optional_filter(self, predicate: Option<P>) -> OptionalFilter<Self, P>

Filters the iterator with the predicate, like filter. If the predicate is None, all items will be returned.

§Examples

Basic usage:

use iter_opt_filter::IteratorOptionalFilterExt;

let mut iter = (0..3).optional_filter(Some(|&item: &usize| item % 2 == 0));
assert_eq!(iter.next(), Some(0));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);
 
let mut iter = (0..3).optional_filter(None::<fn(&usize) -> bool>);
assert_eq!(iter.next(), Some(0));
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

Because the type stays the same, regardless of the predicate being Some or None, the filters are easily chainable:

use iter_opt_filter::IteratorOptionalFilterExt;
 
let mut iter = (0..3)
    .optional_filter(Some(|&item: &usize| item % 2 == 0))
    .optional_filter(None::<fn(&usize) -> bool>)
    .optional_filter(Some(|&item: &usize| item > 1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<I, P> IteratorOptionalFilterExt<P> for I
where I: Iterator, P: FnMut(&I::Item) -> bool,