Why I can't declare a static OnceCell?

Hello,
I don't understand why the following global static declaration is error even I don;t have any multi-thread code? Thank you.

use std::cell::OnceCell;

#[derive(Debug)]
struct Config {
    database_url: String,
    feature_flags: Vec<String>,
}

static CONFIG: OnceCell<Config> = OnceCell::new();

fn main() {
.....
}

The error is as below although no multi-thread codes and I want to use OnceCell for a lazy init:

10 | static CONFIG: OnceCell<Config> = OnceCell::new();
   |                ^^^^^^^^^^^^^^^^^^^ `OnceCell<Config>` cannot be shared between threads safely
   |
   = help: the trait `Sync` is not implemented for `OnceCell<Config>`
   = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead
   = note: shared static variables must have a type that implements `Sync`
1 Like

Statics need to be thread-safe. OnceCell is not thread-safe. You probably want to use std::sync::OnceLock instead.

Even if your code may not seem to use multiple threads, rustc will still assume there may be multiple threads. Rustc doesn't know which C function do and don't spawn new threads.

10 Likes

Thank you, I just read the following text in Rust Reference (Static items - The Rust Reference). My Bad.

The type must have the Sync trait bound to allow thread-safe access.
1 Like