OnceCell and lazy initialization
Quick answer
OnceCell<T> stores a value that can be initialized once through a shared reference. Lazy initialization defers work until a value is first needed, which is useful for computed settings or cached results.
Initialize once through shared access
get returns Option<&T>; set rejects a second initialization and returns the attempted value. get_or_init computes the value only when empty. Exclusive access permits resetting a cell. For synchronized use, see OnceLock; LazyLock stores an initializer that runs when the value is first accessed.
use std::cell::OnceCell;fn main() { let c = OnceCell::new(); println!("empty: {}", c.get().is_none()); c.set(12).unwrap(); println!("second: {:?}", c.set(99)); println!("{:?}", c.get()); }Expected stdout (not executed):
empty: truesecond: Err(99)Some(12)The rejected write does not replace the first value.
use std::cell::OnceCell;fn main() { let c = OnceCell::new(); let first = c.get_or_init(|| 3 * 4); let second = c.get_or_init(|| 99); println!("{first}, {second}"); }Expected stdout (not executed):
12, 12The second initializer is not called.
Common mistake
Do not use OnceCell as a multi-thread synchronization primitive; use OnceLock when appropriate.
Try it yourself
Store a computed label with get_or_init and explain why it is not recomputed on the next access.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
OnceCell and lazy initialization — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A value should be computed only on first access, including concurrent callers. Which synchronized abstraction fits?
OnceCell and lazy initialization — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::cell::OnceCell; fn main() { let c = OnceCell::new(); println!("empty: {}", c.get().is_none()); c.set(12).unwrap(); println!("second: {:?}", c.set(99)); println!("{:?}", c.get()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
OnceCell and lazy initialization — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::cell::OnceCell; fn main() { let c = OnceCell::new(); let first = c.get_or_init(|| 3 * 4); let second = c.get_or_init(|| 99); println!("{first}, {second}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.