为什么错误 "the trait `FnOnce<()>` is implemented but that implementation is not `const`"?
Why the error "the trait `FnOnce<()>` is implemented but that implementation is not `const`"?
我是 Rust 新手。我正在使用 Rust 1.60.0.
我正在尝试使用此代码 (PLAYGROUND HERE):
pub const VERSION: &'static str = option_env!("VERSION").unwrap_or_else(|| "dev");
但我收到此错误:
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`
你能帮我理解它有什么问题吗?
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
因为该函数本身不能在编译时调用。
你可以做的是使用可以评估编译时间的匹配表达式:
pub const VERSION: &'static str = match option_env!("VERSION") {
Some(version) => version,
None => "dev",
};
我是 Rust 新手。我正在使用 Rust 1.60.0.
我正在尝试使用此代码 (PLAYGROUND HERE):
pub const VERSION: &'static str = option_env!("VERSION").unwrap_or_else(|| "dev");
但我收到此错误:
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`
你能帮我理解它有什么问题吗?
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
因为该函数本身不能在编译时调用。 你可以做的是使用可以评估编译时间的匹配表达式:
pub const VERSION: &'static str = match option_env!("VERSION") {
Some(version) => version,
None => "dev",
};