此代码无法编译,因为 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
的两个分支。
这有点 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();
}
}