is it possible to filter on a vector in-place?
Solution 1:
If you want to remove elements, you can use retain()
, which removes elements from the vector if the closure returns false
:
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);
If you want to modify the elements in place, you have to do that in a for x in vec.iter_mut()
.
Solution 2:
If you truly want to mutate the vector's elements while filtering it, you can use the nightly-only method Vec::drain_filter
, an extremely flexible tool:
#![feature(drain_filter)]
fn main() {
let mut vec = vec![1, 2, 3, 4];
vec.drain_filter(|x| {
if *x % 2 == 0 {
true
} else {
*x += 100;
false
}
});
assert_eq!(vec, [101, 103]);
}
It also allows you to get the removed elements as the return value of the entire method is an iterator!