OnceCell stores a value that can be initialized once and accessed afterward. It can defer initialization when a value cannot be created in a single global-scope expression: declare the cell, then initialize it inside a function. This avoids adding a crate dependency, but separating declaration and initialization can reduce clarity and leave competing code paths to handle initialization. section 4.6.4
Listing 4.19 Using std::cell::OnceCell
let popular_baby_names_2017: OnceCell<Vec<String>> = OnceCell::new();
popular_baby_names_2017.get_or_init(|| {
vec![
String::from("Emma"),
String::from("Liam"),
String::from("Olivia"),
String::from("Noah"),
]
});
A small example uses get_or_init to populate a OnceCell<Vec<String>> with popular baby names. section 4.6.4
OnceCell is an interior-mutability container: its contents can change even when the container is immutable. Consider whether that hidden mutability helps before using it for global data or a singleton; passing data as arguments or using dependency injection may be clearer. OnceLock is the standard library’s thread-safe counterpart. section 9.4 section 10.7

