是否可以匹配`const fn`的结果?

K. *_*ann 5 constants pattern-matching rust

我试过天真的方法

fn main() -> Result<(), Box<std::error::Error>> {
    let num = 0;
    match num {
        u64::max_value() => println!("Is u64::max_value()"),
        _ => println!("Is boring")
    }
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

但它失败了expected tuple struct/variant, found method <u64>::max_value

除了n if n == u64::max_value() => ...我可以使用的语法之外,还有其他语法吗?

mca*_*ton 7

的左边部分=>必须是一个模式,很少有表达式也是有效的模式。调用表达式不是有效的模式。

可以匹配命名常量,因此您可以执行以下操作:

fn main() -> Result<(), Box<std::error::Error>> {
    let num = 0;

    const MAX: u64 = u64::max_value();
    match num {
        MAX => println!("Is u64::max_value()"),
        _ => println!("Is boring")
    }
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

链接到游乐场

这还有一个好处是让编译器检查你的匹配是否是详尽的(模式守卫没有):

const fn true_fn() -> bool { true }

fn main() -> Result<(), Box<std::error::Error>> {
    let num = true;

    const TRUE: bool = true_fn();
    match num {
        TRUE => println!("Is u64::max_value()"),
        false => println!("Is boring")
    }
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

链接到游乐场

  • @ÖmerErden 对于这样一个简单的示例,您不需要绑定确定(特别是因为 Boiethios 提醒我们已经存在绑定),但是还有更复杂的示例,我肯定会使用常量项。例如。我有一个传感器,原始值必须在 5 个不同的间隔上进行不同的缩放才能获得实际值,然后我为 3 个中间值创建了一个常量。Rust 中的 `const` 是免费的,不要害怕使用它们。 (3认同)