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?
You can combine iterators to create full
u8
range:In nightly Rust you can use inclusive range:
I think you are comparing different types so need to cast. Try this:
As alex already said, it's probably the best to iterate using bigger integer types (like
u32
) and cast it when comparing to theu8
you're searching for:In this special case you can use a half-open range, too:
The binary representation of 256 is
1_0000_0000
.u8
only saves the 8 rightmost bits, so just0
s. Thus0..256u8
is equivalent to0..0
, which of course is an empty range.