I've tried the naive approach
fn main() -> Result<(), Box<std::error::Error>> {
let num = 0;
match num {
u64::max_value() => println!("Is u64::max_value()"),
_ => println!("Is boring")
}
Ok(())
}
but it fails with expected tuple struct/variant, found method <u64>::max_value
.
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(())
}
Link to playground
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(())
}
Link to playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With