我可以使 `const` 表达式的 `match` 结果也为 `const` 吗?

问题描述 投票:0回答:1

此代码无法编译,因为 rustc 声称

f
需要是
const
:

const FOO: Option<u32> = None;

fn implementation_with_const<const V: u32>() {
    println!("Got {}", V);
}

fn implementation_without_const() {
    println!("Did not get a constant");
}

fn main() {
    match FOO {
        Some(f) => implementation_with_const::<{f}>(),
        None => implementation_without_const(),
    };
}

从所有表现来看,

f
满足成为
const
的所有条件。有什么方法可以重写我的代码,以便我想做的事情成为可能吗? (在我的实际应用中,
FOO
是基于目标机器信息在库中定义的常量,而implementation_with_const()的参数确实需要静态已知,所以我不能简单地内联它,或者转动const参数变成普通的。)

使用不稳定功能

#![feature(const_option)]
并将
{f}
替换为
{FOO.unwrap()}
会导致编译失败(如果
FOO
None
),因为无论
match
如何,都会评估
FOO
的两个分支。

rust constants
1个回答
0
投票

这有点 hacky,需要你有一个 const 的方法来构造内部类型,但这应该可行。

fn main() {
    const FOO_UNWRAP: u32 = if let Some(f) = FOO { f } else { 0 };
    if FOO.is_some() {
        implementation_with_const::<FOO_UNWRAP>();
    } else {
        implementation_without_const();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.