C++ example:
for (long i = 0; i < 101; i++) { //... }
In Rust I tried:
for i: i64 in 1..100 { // ... }
I could easily just declare a let i: i64 =
var before the for loop but I'd rather learn the correct way to doing this, but this resulted in
error: expected one of `@` or `in`, found `:` --> src/main.rs:2:10 | 2 | for i: i64 in 1..100 { | ^ expected one of `@` or `in` here
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
A common identifier naming convention is for the loop counter to use the variable names i, j, and k (and so on if needed), where i would be the most outer loop, j the next inner loop, etc. The reverse order is also used by some programmers.
In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
A for loop's expression in Rust is an iterator that returns a series of values. Each element is one iteration of the loop. This value is then bound to variable and can be used inside the loop code to perform operations.
You can use an integer suffix on one of the literals you've used in the range. Type inference will do the rest:
for i in 1i64..101 { println!("{}", i); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With