How can I specify the type of the loop variable in a for loop?

Viewed 364

I want to specify the type of i in this for loop. Visual Studio Code tells me that the type in i32 but the number isn't that big so I'd like to change it to u8.

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

I tried this:

for i: u8 in 0..101 {
    println!("{}", i);
}

However, I get this error:

error: expected one of `@` or `|`, found `:`
 --> src/main.rs:2:10
  |
2 |     for i: u8 in 0..101 {
  |          ^
  |          |
  |          expected one of `@` or `|`
  |          help: maybe write a path separator here: `::`

What is the right way to specify the type?

2 Answers

It's not possible to have a type annotation in a for-loop, because the for-loop expects a pattern, and a pattern cannot contain type annotations. See the Rust reference for more details.

Instead you can do one of three things:

Make the type of the iterator unambiguous

In this case, it would be:

for i in 0..101u8 {
    println!("{}", i);
}

(playground)

Use an irrefutable pattern with the @-pattern

for i @ 0..=255u8 in 0..101 {
    println!("{}", i);
}

(playground)

Add a type annotation inside the loop:

for i in 0..101 {
    let i: u8 = i;
    println!("{}", i);
}

(playground)

You could explicitly choose the type of any number by adding an underscore followed by the data type.

fn main() {
    for i in 0..101_u8 {
        println!("{}", i);
    }
}
Related