Stepping through an iterator in regular intervals
Have you ever wanted to step through data by only looking at every nth item? On stable Rust, the best solution to this problem is using the third-party crate itertools
(https://crates.io/crates/itertools), which brings you a whole lot of iterator goodies, or allows you to code the functionality yourself; however, you have a built-in step_by
method doing exactly this.
How to do it...
Open the
Cargo.toml
file that has been generated earlier for you.In the
bin
folder, create a file callediterator_step_by.rs
.Add the following code, and run it with
cargo run --bin iterator_step_by
:
1 #![feature(iterator_step_by)] 2 3 fn main() { 4 // step_by() will start on the first element of an iterator, 5 // but then skips a certain number of elements on every iteration 6 let even_numbers: Vec<_> = (0..100).step_by(2).collect(); 7 println!("The first one hundred even numbers: {:?}", even_numbers); 8 9 // step_by...