Suppose you have a Vector
in Rust, and wish to filter out every other element, or every N elements. This is similar to the Nth-child selector from CSS.
The retain function in Rust acts upon an element value, not its index. But we can pass a local variable (and increment that variable) to retain()
.
Consider a Vector
of 4 i32
integers in Rust. When we get every other integer, we want a Vector
that has the first, and third, elements remaining.
Input: 1, 2, 3, 4 Output: 1, 3 (Every Nth(2))
To start, we introduce the every_nth_element
—this receives a Vector
of integers. We call every_nth_element
twice in the program.
Vector
and get every other element—we must pass the argument 2 to indicate "every other."Vector
. Notice how the first and fourth elements, 10 and 40, are the ones remaining here.every_nth_element
we start the index counter "c" at -1 as it is incremented before being tested.fn every_nth_element(values: &mut Vec<i32>, n: i32) { // Retain elements with evenly divisible indexes. let mut c = -1; values.retain(|_| { c += 1; return c % n == 0 }); } fn main() { // Part 1: retain every other element. // Be sure to borrow vectors mutably. let mut values1 = vec![1, 2, 3, 4]; every_nth_element(&mut values1, 2); println!("EVERY OTHER: {:?}", values1); // Part 2: retain every third element. let mut values2 = vec![10, 20, 30, 40, 50, 60]; every_nth_element(&mut values2, 3); println!("EVERY NTH(3): {:?}", values2); }EVERY OTHER: [1, 3] EVERY NTH(3): [10, 40]
We can pass a function argument to retain()
on a vector to keep certain elements in the vector. And we can filter on indexes with a local variable.