retain()
RS-P1009The collections in Rust (Vec
, VecDeque
, HashMap
, HashSet
, etc.)
provide the retain(..)
method to filter elements matching a given predicate
and discard the rest. The drain(..)
method can be used to do the reverse as well.
Consider using this instead of into_iter().filter().collect()
.
fn foo() {
let mut v: Vec<i32> = vec![1, 2, 3, 4];
v = v.into_iter().filter(|x| x % 2 == 0).collect();
let mut dq = VecDeque::from([1, 2, 3, 4]);
dq = dq.into_iter().filter(|x| x % 2 == 0).collect();
}
fn foo() {
let mut v: Vec<i32> = vec![1, 2, 3, 4];
v.retain(|x| x % 2 == 0);
let mut dq = VecDeque::from([1, 2, 3, 4]);
dq.retain(|x| x % 2 == 0);
}