Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
K. Biermann Avatar asked Jan 11 '19 18:01

K. Biermann


1 Answers

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

like image 176
mcarton Avatar answered Oct 20 '22 08:10

mcarton