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
If your loop variable happens to be the result of a function call that returns a generic type:
You can use a turbofish to specify the types:
Or you can use the fully-qualified syntax:
See also:
You can use an integer suffix on one of the literals you've used in the range. Type inference will do the rest:
No, it is not possible to declare the type of the variable in a
for
loop.Instead, a more general approach (e.g. applicable also to
enumerate()
) is to introduce alet
binding by destructuring the item inside the body of the loop.Example: