liveBook · Manning

OnceCell

As explained in Idiomatic Rust

OnceCell is a Rust standard-library cell that permits a value to be initialized at most once and then accessed thereafter.

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

How Idiomatic Rust covers it

How deep it goes
Explains deferred initialization, interior mutability, and tradeoffs, but does not detail implementation internals.
Examples
Uses get_or_init to populate a vector of popular baby names.
What it assumes
Explains Rust's default immutability and introduces interior mutability without assuming prior knowledge of that concept.
What you can do after
Apply OnceCell through get_or_init to initialize a value within a function.
How it connects
Connects OnceCell to interior mutability, thread_local!, OnceLock, global data, and dependency injection.

Also explained in

Compare how 2 books explain OnceCell →

Related concepts

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