How to iterate over every second number

佐手、 提交于 2021-01-27 05:09:15

问题


Reading the docs, I noticed a sentence saying: "Rust doesn't have a C style for loop.". So, I wonder, how can I make a loop equivalent to for(i = 0; i < 10; i += 2) { }?

The ways I can think of are something like:

for i in 0..10 {
    if i % 2 == 0 {
        //Do stuff
    }
}

Or even:

let i = 0;
loop {
    if i < 10 {
        //Do stuff
        i += 2;
    } else {
        break;
    }
}

But I'm not sure this is the best way, especially since it's really verbose. Is there a better way? I'm guessing it would be with iterators, but I'm not sure how I'd do that.


回答1:


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



回答2:


This is now implemented in std with the step_by function

for i in (0..10).step_by(2) {
    // Do stuff
}



回答3:


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);


来源:https://stackoverflow.com/questions/28669607/how-to-iterate-over-every-second-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!