为什么在`u64 % 2`上匹配时没有覆盖`2_u32..=u32::MAX`?

问题描述 投票:0回答:1

如果我尝试构建以下代码:

fn main () {
    let my_val: u32 = 42;
    
    match my_val % 2 {
        0 => println!("We're even now"),
        1 => println!("Well, that's odd"),
    }
}

我会收到以下错误消息:

error[E0004]: non-exhaustive patterns: `2_u32..=u32::MAX` not covered
 --> src/main.rs:4:11
  |
4 |     match my_val % 2 {
  |           ^^^^^^^^^^ pattern `2_u32..=u32::MAX` not covered
  |
  = note: the matched value is of type `u32`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
  |
6 ~         1 => println!("Well, that's odd"),
7 ~         2_u32..=u32::MAX => todo!(),
  |

For more information about this error, try `rustc --explain E0004`.
error: could not compile `playground` (bin "playground") due to 1 previous error

我实在不明白。

2_u32..=u32::MAX
代表什么情况?

rust pattern-matching modular-arithmetic
1个回答
0
投票

这真的很简单。

%
运算符是使用
std::ops::Rem
特征定义的。它的关联类型
Output
定义了该操作的结果是什么。如果 u32
 
Output
实现是
u32
。所以从类型系统的角度来看
Rem::rem
可以返回 any
u32
值。因此,为了使匹配详尽,您必须匹配所有值。

您可以使用

unreachable
宏来指示这些路径是无法访问的。

pub fn foo(x: u32) {
    match x % 2 {
        0 => println!("We're even now"),
        1 => println!("Well, that's odd"),
        _ => unreachable!("u32 mod 2 can only return 0 or 1"),
    }
}

请注意,第三个分支很容易优化,并且编译器将在发布版本中执行此操作。您可以使用 goldbolt 检查生成的 ASM。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.