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

ぃ、小莉子 提交于 2020-04-07 05:07:46

问题


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:


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



来源:https://stackoverflow.com/questions/54152207/is-it-possible-to-match-against-the-result-of-a-const-fn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!