如何迭代所有字节值(`0..256`中的overflowing_literals)

Per*_*ids 4 rust

我正在尝试迭代所有可能的byte(u8)值.不幸的是在我的范围内的文字0..256被强制转换为u8256溢出:

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

以上编译:

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
Run Code Online (Sandbox Code Playgroud)

第一个循环体永远不会被执行.

由于演员阵容,我的解决方法非常难看并且感觉很脆弱:

for short in 0..256 {
    let _explicit_type: u16 = short;
    foo(short as u8);
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

por*_*omp 9

从 Rust 1.26 开始,包含范围使用语法稳定..=,因此您可以将其写为:

for byte in 0..=255 {
    foo(byte);
}
Run Code Online (Sandbox Code Playgroud)


Mat*_* M. 5

这是问题无法创建具有最大值的范围.

它的要点是byte被推断为u8,因此0..256被表示为Range<u8>但不幸的是256溢出为u8.

目前的解决方法是使用更大的整数类型并在u8以后进行转换,因为256实际上从未达到过.

包含范围...RFC已进入最终评论期; 也许将来它有可能拥有for byte in 0...255或替代它(0..255).inclusive().