Description
Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=67155cb72a24e0a080d9dee88483fbec
use std::sync::Mutex;
static MUTEX: Mutex<i32> = Mutex::new(1);
fn main() {
println!("{}", MUTEX.lock().unwrap());
}
The current output is:
error[E0015]: cannot call non-const fn `Mutex::<i32>::new` in statics
--> src/main.rs:3:28
|
3 | static MUTEX: Mutex<i32> = Mutex::new(1);
| ^^^^^^^^^^^^^
|
= note: calls in statics are limited to constant functions, tuple structs and tuple variants
I have a friend learning rust who concluded, reasonably, that global mutexes are not allowed and you have to declare them in main
and pass them down to functions with an argument. It would be great if the compiler could suggest the common alternative approach instead, which is lazy initialization:
Ideally the output should look like:
error[E0015]: cannot call non-const fn `Mutex::<i32>::new` in statics
--> src/main.rs:3:28
|
3 | static MUTEX: Mutex<i32> = Mutex::new(1);
| ^^^^^^^^^^^^^
|
= note: calls in statics are limited to constant functions, tuple structs and tuple variants
= help: consider using the `once_cell` crate: https://crates.io/crates/once_cell
I know the compiler generally has a policy of not favoring individual crates, but once_cell is literally becoming part of the standard library so I think this is reasonable and doesn't show favoritism.
(I'm aware Mutex::new will be a const fn
in 1.63, but this same diagnostic would be helpful in any other case where the initializer isn't const.)