liveBook · Manning

Once_cell

As explained in Learn Rust in a Month of Lunches

once_cell is a Rust crate that provides lazily initialized single-assignment and mutable cell abstractions for values that cannot be initialized as compile-time constants.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains lazy runtime initialization and its motivation, but does not show a once_cell API example.
Examples
Uses a global logger containing a Mutex, String URL, HTTP client, and log records to expose non-const initialization errors.
What it assumes
Assumes basic Rust statics and const functions, while defining lazy initialization through runtime construction.
What you can do after
Evaluate when lazy global initialization is needed instead of direct static initialization.
How it connects
Connects lazy initialization with global variables, const functions, lazy_static, and standard-library functionality.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.