Removing elements from a Vec based on some condition [duplicate]

If you look at the interface of Vec, you will not find a method that erases some elements based on a predicate. Instead you will find retain which keeps the elements based on a predicate.

Of course, both are symmetric, it’s just that retain is harder to find if you filter method names by “remove” or “erase” (it does contain “remove” in its description).

The example provided speaks for itself:

let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);

Leave a Comment