@Timmmm's and @Hauleth's answers are quite pragmatic I wanted to provide a couple of alternatives.
Here's a playground with some benchmarks and tests:
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=cffc3c39c4b33d981a1a034f3a092e7b
This is ugly, but if you really want a v.retain_with_index()
method, you could do a little copy-pasting of the retain
method with a new trait:
trait IndexedRetain<T> {
fn retain_with_index<F>(&mut self, f: F)
where
F: FnMut(usize, &T) -> bool;
}
impl<T> IndexedRetain<T> for Vec<T> {
fn retain_with_index<F>(&mut self, mut f: F)
where
F: FnMut(usize, &T) -> bool, // the signature of the callback changes
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;
for i in 0..len {
// only implementation change here
if !f(i, &v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}
}
such that the example would look like this:
v.retain_with_index(|index, item| (index % 2 == 0) || item == 4);
Or... better yet, you could use a higher-order function:
fn with_index<T, F>(mut f: F) -> impl FnMut(&T) -> bool
where
F: FnMut(usize, &T) -> bool,
{
let mut i = 0;
move |item| (f(i, item), i += 1).0
}
such that the example would now look like this:
v.retain(with_index(|index, item| (index % 2 == 0) || item == 4));
(my preference is the latter)