once_cell provides lazily initialized storage for values that cannot be created as compile-time constants. Lazy initialization means creating the value at runtime, when it is first needed. section 17.7
Use once_cell when a program needs global state whose construction requires ordinary runtime operations:
- Create global variables that cannot be initialized with const functions. section 17.7
- Defer initialization until runtime instead of constructing the value during compilation. section 17.7
- Choose a more flexible, though somewhat harder-to-use, alternative to lazy_static. section 17.7.1
A global logger with runtime-only values
A global Logger may contain a String created with to_string and a reqwest Client created with Client::default. A direct static declaration fails because these are not const functions. Lazy initialization solves this kind of global construction by creating the value at runtime. section 17.7.1
static GLOBAL_LOGGER: Mutex<Vec<Log>> = Mutex::new(Vec::new());
Compare a const-capable global Mutex value with runtime-initialized globals that require lazy initialization. section 17.7
