'Why the error "the trait `FnOnce<()>` is implemented but that implementation is not `const`"?
I'm new to Rust. I'm using rust 1.60.0.
I'm trying to use this code (PLAYGROUND HERE):
pub const VERSION: &'static str = option_env!("VERSION").unwrap_or_else(|| "dev");
but I'm getting this error:
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`
Can you help me understand what's wrong with it?
Solution 1:[1]
const is meant for compile time evaluation, not all functions can be evaluated at compile time, which is why it is requiring a const FnOnce but const FnOnce are limited, you can learn more here of what can be evaluated compile time: https://doc.rust-lang.org/reference/const_eval.html In your case, even if you use a const fn you'll still get the error:
error: `Option::<T>::unwrap_or_else` is not yet stable as a const fn
as that function itself can't be called at compile time. What you can do is use the match expression which can be evaluated compile time:
pub const VERSION: &'static str = match option_env!("VERSION") {
Some(version) => version,
None => "dev",
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oussama Gammoudi |
