What is the idiomatic way to write a for loop without using the iterator value?

試著忘記壹切 提交于 2019-12-21 06:47:48

问题


Assuming I want a finite loop using a range:

let mut x: i32 = 0;
for i in 1..10 {
    x += 1;
}

The compiler will spit out the warning:

warning: unused variable: `i`, #[warn(unused_variables)] on by default
for i in 1..10 {
    ^

Is there a more idiomatic way to write this that won't make the compiler complain?


回答1:


You can write _ as your pattern, meaning “discard the value”:

let mut x: i32 = 0;
for _ in 1..10 {
    x += 1;
}


来源:https://stackoverflow.com/questions/29932503/what-is-the-idiomatic-way-to-write-a-for-loop-without-using-the-iterator-value

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