K. Biermann
K. Biermann

Reputation: 1318

Is it possible to match against the result of a `const fn`?

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?

Upvotes: 10

Views: 5673

Answers (1)

mcarton
mcarton

Reputation: 30061

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

Upvotes: 13

Related Questions