Nth element. 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().
Output requirement. 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.
Part 1 We filter the Vector and get every other element—we must pass the argument 2 to indicate "every other."
Part 2 We get every third element from the Vector. Notice how the first and fourth elements, 10 and 40, are the ones remaining here.
Info In 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.