0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
meisterluk
  • 804
  • 10
  • 19
  • Thank you @Shepmaster, this is a duplicate. Sorry for improper search for duplicates. It seems that iterating over a larger type and casting is the idiomatic way to go. https://stackoverflow.com/a/40421720/1624929 – meisterluk Jun 04 '17 at 14:08
  • 2
    No worries. Inclusive ranges are [getting closer and closer, though](https://github.com/rust-lang/rust/issues/28237)! – Shepmaster Jun 04 '17 at 14:19

0 Answers0