Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 如何迭代每一秒的数字_Loops_Rust - Fatal编程技术网

Loops 如何迭代每一秒的数字

Loops 如何迭代每一秒的数字,loops,rust,Loops,Rust,在阅读文档时,我注意到一句话:“Rust没有C风格的循环。”。所以,我想知道,我怎样才能使循环等价于(I=0;I

在阅读文档时,我注意到一句话:“Rust没有C风格的循环。”。所以,我想知道,我怎样才能使循环等价于(I=0;I<10;I+=2){}

我能想到的方法是:

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

let i = 0;
loop {
    if i < 10 {
        //Do stuff
        i += 2;
    } else {
        break;
    }
}
设i=0;
环路{
如果我<10{
//做事
i+=2;
}否则{
打破
}
}
但我不确定这是不是最好的方式,特别是因为它确实很冗长。有更好的办法吗?我猜迭代器应该是这样的,但我不知道该怎么做

现在有,但它被标记为不稳定,带有消息“可能被范围符号和适配器所取代”

印刷品

0
2
4
6
8
提供了您想要的abitrary迭代器。创建一个迭代器,在每次迭代后跳过
n-1
元素

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

这现在在std中通过


注:@ker使用
itertools
在范围表示法上实现了替代方案。
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);
for i in (0..10).step_by(2) {
    // Do stuff
}