Use `once_cell::sync::Lazy` to define static variables that compute their value only on first access for efficient lazy initialization.
Use once_cell::sync::Lazy for thread-safe lazy initialization or once_cell::unsync::Lazy for single-threaded contexts. Define a static variable with the Lazy type, providing the value to compute and the type to store.
use once_cell::sync::Lazy;
static COUNT: Lazy<usize> = Lazy::new(|| {
println!("Initializing count...");
42
});
fn main() {
println!("Count is {}", *COUNT);
}
The once_cell crate lets you create variables that calculate their value only the first time you access them. This saves resources by avoiding expensive setup work until it is actually needed. Think of it like a vending machine that only brews coffee when you press the button, rather than keeping a fresh cup ready for everyone all the time.