Fred Hors
Fred Hors

Reputation: 4116

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?

Upvotes: 1

Views: 711

Answers (1)

Oussama Gammoudi
Oussama Gammoudi

Reputation: 761

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",
};

Upvotes: 5

Related Questions