Literal out of range warning when iterating over a

2020-04-07 18:46发布

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?

标签: rust
3条回答
Ridiculous、
2楼-- · 2020-04-07 18:59

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 {
    //...
}
查看更多
祖国的老花朵
3楼-- · 2020-04-07 19:16

I think you are comparing different types so need to cast. Try this:

for num in 0..256 {
    let y = num as u8;
    if y == a {
        println!("found");
        break;
    }
}
查看更多
ら.Afraid
4楼-- · 2020-04-07 19:21

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.

查看更多
登录 后发表回答