Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

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

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

fn foo(byte: u8) {
    println!("{}", byte);
}

fn main() {
    for byte in 0..256 {
        foo(byte);
        println!("Never executed.");
    }
    for byte in 0..1 {
        foo(byte);
        println!("Executed once.");
    }
}

The above compiles with:

warning: literal out of range for u8
 --> src/main.rs:6:20
  |
6 |     for byte in 0..256 {
  |                    ^^^
  |
  = note: #[warn(overflowing_literals)] on by default

The first loop body is never executed at all.

My workaround is very ugly and feels brittle because of the cast:

for short in 0..256 {
    let _explicit_type: u16 = short;
    foo(short as u8);
}

Is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...