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?