How to use once_cell and LazyLock for one-time initialization

Use std::sync::LazyLock for thread-safe one-time initialization in Rust 1.94.0+ or once_cell for older versions.

Use std::sync::LazyLock for thread-safe, one-time initialization of global values in Rust 1.94.0 and later, or once_cell::sync::Lazy for older versions or non-standard types. LazyLock is now stabilized in the standard library and handles initialization automatically on first access.

use std::sync::LazyLock;

static CONFIG: LazyLock<String> = LazyLock::new(|| {
    // Expensive initialization logic runs only once
    "initialized value".to_string()
});

fn main() {
    println!("{CONFIG}"); // Triggers initialization
    println!("{CONFIG}"); // Uses cached value
}

For non-thread-safe single-threaded contexts, use std::cell::LazyCell (stabilized in 1.94.0) or once_cell::unsync::Lazy.