彻底匹配涉及“大于”情况的一系列整数

Ste*_*fer 2 rust

考虑一个带有内置整数常量const N: u64和运行时整数值的 Rust 程序x: u64。我想进行匹配,x使x < N每个值都有一个单独的特殊情况。此外,还应该分别有一个单独的 case forx == N和一个 for x > N。我的第一次尝试是这样的:

const N: u64 = 3;

match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N => println!("Equal"),
    _ => println!("Larger"),
}
Run Code Online (Sandbox Code Playgroud)

这是可行的,但它有以下缺点:想象一下,我将常量的值增加到N = 4但忘记添加新的特殊情况x = 3。上面的代码不会在编译时捕捉到这一点,因为最后一个匹配模式 ( _) 也覆盖了被遗忘的情况,并且代码会默默地中断。所以我正在寻找一种具有这种编译时保证的解决方案。

为了实现这一点,最后一个案例应该只匹配x > N,所以我尝试使用一个if条件:

match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N => println!("Equal"),
    _ if x > N => println!("Larger"),
}
Run Code Online (Sandbox Code Playgroud)

但现在我从 Rust 得到一个错误,表明匹配并不详尽,我认为这是由于编译器不够聪明来分析条件if。虽然分析范围足够聪明,但我不知道如何将最后一种情况表示为范围。它必须是类似的东西(N+1)..=u64::MAX,但由于加号的原因,实际上并不能编译。

到目前为止,我最好的解决方案是使用嵌套匹配,如下所示。这似乎有效,并且在N更改时也会给出所需的编译时错误,但我想知道是否有更优雅的解决方案。

match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N..=u64::MAX => match x {
        N => println!("Equal"),
        _ => println!("Larger")
    }
}
Run Code Online (Sandbox Code Playgroud)

Jmb*_*Jmb 5

你可以这样做:

match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N => println!("Equal"),
    N.. => println!("Larger"),
}
Run Code Online (Sandbox Code Playgroud)

操场