Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal out of range warning when iterating over all values of u8 [duplicate]

Tags:

rust

The range in a for-loop, as I understand, is lower-limit inclusive and upper-limit exclusive. This is introducing an issue in the following code:

fn main() {
    let a: u8 = 4;

    for num in 0..256 {
        if num == a {
            println!("match found");
            break;
        }
    }
}

I want to loop 256 times from 0 to 255, and this fits into the range of data supported by u8. But since the range is upper limit exclusive, I have to give 256 as the limit to process 255. Due to this, the compiler gives the following warning.

warning: literal out of range for u8
 --> src/main.rs:4:19
  |
4 |     for num in 0..256 {
  |                   ^^^
  |
  = note: #[warn(overflowing_literals)] on by default

When I execute this, the program skips the for loop.

In my opinion, the compiler has to ignore 256 in the range and accept the range as u8 range. Is it correct? Is there any other way to give the range?

like image 672
Steve Avatar asked Dec 24 '22 23:12

Steve


2 Answers

You can combine iterators to create full u8 range:

use std::iter::once;
for i in (0..255).chain(once(255)){
    //...
}

In nightly Rust you can use inclusive range:

#![feature(inclusive_range_syntax)]
for i in 0...255 {
    //...
}
like image 140
aSpex Avatar answered Dec 31 '22 02:12

aSpex


As alex already said, it's probably the best to iterate using bigger integer types (like u32) and cast it when comparing to the u8 you're searching for:

let a: u8 = 4;

for num in 0..256 {
    if (num as u8) == a {
        println!("match found");
        break;
    }
}

In this special case you can use a half-open range, too:

let a: u8 = 4;

for num in 0.. {
    if num == a {
        println!("match found");
        break;
    }
}

Also when I execute this, the program skips the for loop.

The binary representation of 256 is 1_0000_0000. u8 only saves the 8 rightmost bits, so just 0s. Thus 0..256u8 is equivalent to 0..0, which of course is an empty range.

like image 37
Lukas Kalbertodt Avatar answered Dec 31 '22 01:12

Lukas Kalbertodt