我是 Rust 新手。我正在使用 Rust 1.60.0。
我正在尝试使用此代码(PLAYGROUND HERE):
pub const VERSION: &'static str = option_env!("VERSION").unwrap_or_else(|| "dev");
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
the trait bound `[closure@src\constants.rs:4:81: 4:89]: ~const FnOnce<()>` is not satisfied
the trait `~const FnOnce<()>` is not implemented for `[closure@src\constants.rs:4:81: 4:89]`
wrap the `[closure@src\constants.rs:4:81: 4:89]` in a closure with no arguments: `|| { /* code */ }`rustcE0277
constants.rs(4, 66): the trait `FnOnce<()>` is implemented for `[closure@src\constants.rs:4:81: 4:89]`, but that implementation is not `const`
option.rs(797, 12): required by a bound in `Option::<T>::unwrap_or_else`
Run Code Online (Sandbox Code Playgroud)
你能帮我理解它出了什么问题吗?
const 用于编译时评估,并非所有函数都可以在编译时评估,这就是为什么它需要 const FnOnce 但 const FnOnce 是有限的,您可以在这里了解更多可以在编译时评估的内容: https:// doc.rust-lang.org/reference/const_eval.html 在您的情况下,即使您使用 const fn 您仍然会收到错误:
error: `Option::<T>::unwrap_or_else` is not yet stable as a const fn
Run Code Online (Sandbox Code Playgroud)
因为该函数本身无法在编译时调用。您可以做的是使用可以在编译时评估的匹配表达式:
pub const VERSION: &'static str = match option_env!("VERSION") {
Some(version) => version,
None => "dev",
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
644 次 |
| 最近记录: |