Consider this example:
fn main() {
let mut t: [u8; 256] = [0; 256];
for i in 0..256u8 {
t[i as usize] = i;
}
println!("{}", t[0]);
println!("{}", t[1]);
println!("{}", t[128]);
println!("{}", t[254]);
println!("{}", t[255]);
}
(code sample on play.rust-lang.org)
I want to initialize my array containing 256 values of unsigned integer of 8 bits. The initial value is defined by 0 for the first item and incremented for every successive element.
This code does not work.
The upper bound of the Range
is exclusive, so the for loop's first value is 0, the last value is 255. My array has a length of 256 with indices ranging from first index 0 to last index 255. Sounds fine, but the upper limit is defined as "256u8" (a u8
), a value which is technically 0 (256 % 256 == 0
). Therefore the compiler warns me:
warning: literal out of range for u8
--> <anon>:3:17
|
3 | for i in 0..256u8 {
| ^^^^^
|
= note: #[warn(overflowing_literals)] on by default
What is the most Rust-idiomatic way to overcome this warning?
Disclaimer: This is not a problem. It is just a warning and can easily solved with casts or a single assignment after the loop. I am asking about an idiom.