Warning over range when repeating all u8 values

The range in for-loop, as I understand it, is the lower limit inclusive and excludes the upper limit. This introduces the problem into the following code:

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

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

I want the loop 256 times from 0 to 255, and this fits into the range of data supported u8. But since the range is the exclusive upper limit, I have to provide 256 as the limit for processing 255. In this regard, 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 do this, the program skips the loop for.

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

+4
3

, (, u32) u8, :

let a: u8 = 4;

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

:

let a: u8 = 4;

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

, , for.

256 1_0000_0000. u8 8 , 0 s. , 0..256u8 0..0, , , .

+4

u8:

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

:

#![feature(inclusive_range_syntax)]
for i in 0...255 {
    //...
}
+4

I think you are comparing different types, so they need to be distinguished. Try the following:

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

Source: https://habr.com/ru/post/1659813/


All Articles