In Rust is it possible to operate on a vector in-place?
I'd like to remove some elements from a
vec.iter().filter().collect() creates a new vector with borrowed items.
I'd like to mutate the original
Vec without extra memory allocation (and keep memory of removed elements as an extra capacity of the vector).
Best How To :
If you want to remove elements you can use
retain(), which removes elements from the vector if the filter function return 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 there is map_in_place() but currently is unstable, so you have to do that in a
for x in vec.iter_mut() way.