我试图迭代所有可能的字节(u8)值。不幸的是,我在0..256中的范围文本被转换为u8和256溢出:
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.");
}
}上述汇编的内容如下:
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根本不执行第一个循环体。
我的解决办法很难看,而且由于演员的原因,我觉得很脆弱:
for short in 0..256 {
let _explicit_type: u16 = short;
foo(short as u8);
}有更好的办法吗?
发布于 2015-08-30 12:39:19
这是问题Unable to create a range with max value。
它的要点是,byte被推断为u8,因此0..256被表示为Range<u8>,但不幸的是256溢出为u8。
当前的工作是使用更大的整数类型,并在以后将其转换为u8,因为实际上从未达到256。
有一个...已经进入了最后的评论期;也许在将来有可能有for byte in 0...255或它的替代(0..255).inclusive()。
发布于 2018-05-11 22:14:14
从Rust 1.26开始,使用语法..=稳定包含范围,因此您可以将其编写为:
for byte in 0..=255 {
foo(byte);
}https://stackoverflow.com/questions/32296410
复制相似问题