9

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

10

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

7
  • 1
    But it is not possible to use a const fn-call directly as pattern? Jan 11, 2019 at 18:51
  • 1
    No, there is no some::path() pattern as there is a some::path() expression.
    – mcarton
    Jan 11, 2019 at 18:54
  • 1
    You already have std::u64::MAX. You don't need to create your own binding.
    – Boiethios
    Jan 11, 2019 at 19:19
  • 3
    @Ö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.
    – mcarton
    Jan 11, 2019 at 19:25
  • 1
    @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.
    – mcarton
    Oct 4 at 22:02

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.