What is the idiomatic way to write a for loop with

2020-07-01 02:53发布

问题:

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


标签: rust