Skip to content

Suggest lazy initialization when calling a non-const function in a static initializer #100410

Closed
@jyn514

Description

@jyn514

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.)

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsE-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions