Cannot call non-const fn Mutex::<Option<(u8, u16)>>

Hi

What does this problem mean? I don't get it.

error[E0015]: cannot call non-const fn Mutex::<Option<(u8, u16)>>::new in statics
--> src/main.rs:11:66
|
11 | static GATTS_CREATE_SVC: Mutex<Option<(esp_gatt_if_t, u16)>> = Mutex::new(Option::None);
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: calls in statics are limited to constant functions, tuple structs and tuple variants

The initializer of a static will be baked into the executable, so it must be evaluatable at compile time. Mutex::new() cannot be evaluated at compile time. Use once_cell::sync::Lazy to solve this kind of problem.

Mutex::new is const since 1.63. What version of rustc are you using? Perhaps you just need to update.

1 Like

Well, 1.63 is the latest version and it was released less than a month ago. It's entirely reasonable that not everyone uses (or wants to use) it.

(I for example always try to compile my crates with a rustc several versions behind the latest, to ensure backward compatibility. Sometimes it's not possible or very inconvenient to update an entire toolchain just because some particular piece of code buried deep down in dependencies wants to use some new feature.)

that's exactly what I thought. does Lazy_static library help ?

Yes, But sometimes you should migrate from older to new versions.

You can use lazy_static yes. The once_cell API is being added to the standard library though, so people often choose it instead in new projects so they can use the std version easily when it is stabilized.

Yes, it does, but I prefer once_cell because it doesn't require macros. (They way lazy_static unconditionally creates a reference and a proxy type that is named identically as the variable itself can be inconvenient/confusing, and if the same functionality can be achieved without a macro, it probably should.)