How to iterate over all byte values (overflowing_literals in `0..256`)

后端 未结 2 1433
不思量自难忘°
不思量自难忘° 2020-12-11 18:21

I\'m trying to iterate over all possible byte (u8) values. Unfortunately my range literals in 0..256 are cast to u8 and 256

相关标签:
2条回答
  • 2020-12-11 18:36

    As of Rust 1.26, inclusive ranges are stabilized using the syntax ..=, so you can write this as:

    for byte in 0..=255 {
        foo(byte);
    }
    
    0 讨论(0)
  • 2020-12-11 18:49

    This is issue Unable to create a range with max value.

    The gist of it is that byte is inferred to be u8, and therefore 0..256 is represented as a Range<u8> but unfortunately 256 overflows as an u8.

    The current work-around is to use a larger integral type and cast to u8 later on since 256 is actually never reached.

    There is a RFC for inclusive range with ... which has entered final comment period; maybe in the future it'll be possible to have for byte in 0...255 or its alternative (0..255).inclusive().

    0 讨论(0)
提交回复
热议问题