How to iterate over every second number
There's std::iter::range_step
right now, but it's marked as unstable with the message "likely to be replaced by range notation and adapters".
fn main() {
for i in std::iter::range_step(0, 10, 2) {
println!("{:?}", i);
}
}
prints
0
2
4
6
8
the itertools crate offers what you want for abitrary iterators. The step function creates an iterator that skips n-1
elements after each iteration.
use itertools::Itertools;
let mut it = (0..10).step(2);
assert_eq!(it.next(), Some(0));
assert_eq!(it.next(), Some(2));
assert_eq!(it.next(), Some(4));
assert_eq!(it.next(), Some(6));
assert_eq!(it.next(), Some(8));
assert_eq!(it.next(), None);
This is now implemented in std with the step_by function
for i in (0..10).step_by(2) {
// Do stuff
}