Trait drain_filter_polyfill::VecExt
source · pub trait VecExt<T> {
// Required method
fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F> ⓘ
where F: FnMut(&mut T) -> bool;
}
Expand description
An extension trait to make drain_filter
accessible, implemented for Vec
.
Required Methods§
sourcefn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F> ⓘwhere
F: FnMut(&mut T) -> bool,
fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F> ⓘwhere F: FnMut(&mut T) -> bool,
Creates an iterator which uses a closure to determine if an element should be removed.
If the closure returns true, then the element is removed and yielded. If the closure returns false, the element will remain in the vector and will not be yielded by the iterator.
Using this method is equivalent to the following code:
let mut i = 0;
while i < vec.len() {
if some_predicate(&mut vec[i]) {
let val = vec.remove(i);
// your code here
} else {
i += 1;
}
}
But drain_filter
is easier to use. drain_filter
is also more efficient,
because it can backshift the elements of the array in bulk.
Note that drain_filter
also lets you mutate every element in the filter closure,
regardless of whether you choose to keep or remove it.
Examples
Splitting an array into evens and odds, reusing the original allocation:
use drain_filter_polyfill::VecExt;
let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
let odds = numbers;
assert_eq!(evens, vec![2, 4, 6, 8, 14]);
assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);