10

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?

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

7 Comments

But it is not possible to use a const fn-call directly as pattern?
No, there is no some::path() pattern as there is a some::path() expression.
You already have std::u64::MAX. You don't need to create your own binding.
@ÖmerErden For such a simple example, you don't need a binding sure (especially since one already exist as Boiethios reminded us), but there are more complicated examples where I'd definitely use constant items. Eg. I have a sensor were the raw value has to be scaled differently on 5 different intervals to get the actual value, then I created a constant for the 3 mid values. consts in Rust come at no cost, don't be afraid to use them.
@TurtlesAreCute it's being worked on as part of const expressions and patterns. The syntax requires an explicit const { … } to disambiguate it and at the moment it requires a nightly compiler and explicitly enabled features but it's already implemented to some extent.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.