如何遍历第二个数字 [英] How to iterate over every second number
本文介绍了如何遍历第二个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在阅读文档时,我注意到一句话:"Rust没有 C风格用于循环.".因此,我想知道如何使循环等效于 for(i = 0; i< 10; i + = 2){}
?
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) { }
?
我能想到的方法是:
for i in 0..10 {
if i % 2 == 0 {
//Do stuff
}
}
甚至:
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.
推荐答案
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);
}
}
打印
0
2
4
6
8
这篇关于如何遍历第二个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文