有可能与const fn的结果相匹配吗? [英] Is it possible to match against the result of a `const fn`?
本文介绍了有可能与const fn的结果相匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试过幼稚的方法
fn main() -> Result<(), Box<std::error::Error>> {
let num = 0;
match num {
u64::max_value() => println!("Is u64::max_value()"),
_ => println!("Is boring")
}
Ok(())
}
,但是它失败,并出现个预期的元组结构/变量,找到方法< u64> ::: max_value
。
but it fails with expected tuple struct/variant, found method <u64>::max_value
.
如果n == u64 :: max_value()=>是否有除 n之外的另一种语法? ...
我可以使用?
Is there another syntax except n if n == u64::max_value() => ...
which can I use?
推荐答案
的左侧=>
必须是一个模式,很少有表达式也是有效的模式。调用表达式不是有效的模式。
The left part of =>
must be a pattern, and few expressions are also valid patterns. A call-expression is not a valid pattern.
可以匹配命名常量,因此可以执行以下操作:
Named constants can be matched so you can do this:
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(())
}
这还具有让编译器检查您的匹配是否详尽的优势(这种模式可以保护不要):
This also has the advantage of letting the compiler check whether your matching is exhaustive (which pattern guards don't):
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(())
}
这篇关于有可能与const fn的结果相匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文