迭代 u8 的所有值时出现文字超出范围警告 [英] Literal out of range warning when iterating over all values of u8

查看:28
本文介绍了迭代 u8 的所有值时出现文字超出范围警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for 循环中的范围,据我所知,包含下限和不包含上限.这在以下代码中引入了一个问题:

fn main() {让 a: u8 = 4;对于 0..256 中的 num {如果数字 == 一个 {println!("找到匹配项");休息;}}}

我想从 0 到 255 循环 256 次,这符合 u8 支持的数据范围.但是由于范围是不包括上限的,所以我不得不给出256作为处理255的限制.因此,编译器给出了以下警告.

警告:文字超出 u8 的范围-->src/main.rs:4:19|4 |对于 0..256 中的 num {|^^^|= 注意:#[warn(overflowing_literals)] 默认开启

当我执行这个时,程序会跳过 for 循环.

在我看来,编译器必须忽略范围内的 256 并将范围接受为 u8 范围.这是正确的吗?有没有其他方法可以给出范围?

解决方案

正如alex 已经说过的,最好使用更大的整数类型(如 u32)进行迭代并在与u8 您正在搜索:

设一个:u8 = 4;对于 0..256 中的 num {if (num as u8) == a {println!("找到匹配项");休息;}}

在这种特殊情况下,您可以使用半开范围 也是:

设一个:u8 = 4;对于 0 中的 num.. {如果数字 == 一个 {println!("找到匹配项");休息;}}

<块引用>

此外,当我执行此操作时,程序会跳过 for 循环.

256 的二进制表示是 1_0000_0000.u8 只保存最右边的 8 位,所以只有 0 s.因此0..256u8等价于0..0,当然是空范围.

The range in a for-loop, as I understand, is lower-limit inclusive and upper-limit exclusive. This is introducing an issue in the following code:

fn main() {
    let a: u8 = 4;

    for num in 0..256 {
        if num == a {
            println!("match found");
            break;
        }
    }
}

I want to loop 256 times from 0 to 255, and this fits into the range of data supported by u8. But since the range is upper limit exclusive, I have to give 256 as the limit to process 255. Due to this, the compiler gives the following warning.

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

When I execute this, the program skips the for loop.

In my opinion, the compiler has to ignore 256 in the range and accept the range as u8 range. Is it correct? Is there any other way to give the range?

解决方案

As alex already said, it's probably the best to iterate using bigger integer types (like u32) and cast it when comparing to the u8 you're searching for:

let a: u8 = 4;

for num in 0..256 {
    if (num as u8) == a {
        println!("match found");
        break;
    }
}

In this special case you can use a half-open range, too:

let a: u8 = 4;

for num in 0.. {
    if num == a {
        println!("match found");
        break;
    }
}

Also when I execute this, the program skips the for loop.

The binary representation of 256 is 1_0000_0000. u8 only saves the 8 rightmost bits, so just 0s. Thus 0..256u8 is equivalent to 0..0, which of course is an empty range.

这篇关于迭代 u8 的所有值时出现文字超出范围警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆