Set variable type to usize in for loop

If I write:

        for v in 0..=8 {


v will be infered as i32, how can I set it to usize or u32? Thanks!

     // this is not legal
        for v:usize in 0..=8 {


The integer literals can be typed like 0u32 or 8u32, or both.

1 Like

Thank you! Can I set it to usize?

Sure, use 8usize.

You can also use an underscore if you feel it makes it clearer: 8_usize.

1 Like

Yes! Underscore is clearer!


Another, slightly weird, way you can do this:

for v in 0..100 {
    let v: usize = v;
    println!("{}", v.wrapping_sub(10));

Taking advantage of shadowing and inference to back-propagate the type you wanted in the range.

(Personally, though, I'd use the 0_usize way.)


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.