HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

Is it possible to declare the type of the variable in Rust for loops?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
possiblethedeclareforvariablerustloopstype

Problem

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

Solution

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

Code Snippets

for i in 1i64..101 {
    println!("{}", i);
}

Context

Stack Overflow Q#24463655, score: 69

Revisions (0)

No revisions yet.