Rust Reference ยท Smart Pointers and Memory
Rust OnceCell and LazyCell
Reference for std::cell::OnceCell and LazyCell: set once, get_or_init, lazy values computed on first use, and the thread-safe OnceLock and LazyLock.
OnceCell<T> is a cell that can be written exactly once. It starts empty; the first successful set or get_or_init stores a value, and from then on you can only read it, through a plain shared reference. LazyCell<T, F> wraps that idea around a closure: the value is computed automatically the first time you dereference it.
Both live in std::cell and are single-threaded. Their thread-safe equivalents are std::sync::OnceLock and std::sync::LazyLock, which are what you use for global statics. All four are stable (OnceCell and OnceLock since 1.70, LazyCell and LazyLock since 1.80).
use std::cell::OnceCell; let cell: OnceCell<String> = OnceCell::new(); let value = cell.get_or_init(|| "computed once".to_string());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> OnceCell<T> { pub const fn new() -> OnceCell<T>; pub fn get(&self) -> Option<&T>; pub fn get_mut(&mut self) -> Option<&mut T>; pub fn set(&self, value: T) -> Result<(), T>; pub fn get_or_init<F: FnOnce() -> T>(&self, f: F) -> &T; pub fn take(&mut self) -> Option<T>; pub fn into_inner(self) -> Option<T>; } impl<T, F: FnOnce() -> T> LazyCell<T, F> { pub const fn new(f: F) -> LazyCell<T, F>; pub fn force(this: &LazyCell<T, F>) -> &T; } // LazyCell<T, F> implements Deref<Target = T>
| Item | Description |
|---|---|
OnceCell::new() |
Empty cell. |
set(v) |
Ok(()) if empty, Err(v) if already initialized. |
get() |
Some(&T) once initialized. |
get_or_init(f) |
Returns the value, running f first only if the cell is empty. |
take(&mut self) |
Empties the cell and returns the old value (needs exclusive access). |
LazyCell::new(f) |
Defers f until the first dereference or LazyCell::force. |
Edge cases. If an initializer for get_or_init panics, the cell stays empty. Calling get_or_init re-entrantly from inside its own initializer is a bug: it panics (or deadlocks in the Lock versions). If a LazyCell initializer panics, the cell is poisoned and every later access panics.
Usage notes
- Use
OnceCellfor a field that is expensive to compute and rarely needed, inside a struct that is otherwise shared immutably (memoized length, parsed form of a string). - Use
LazyLockforstaticglobals such as lookup tables or compiled regexes; it replaces most of whatlazy_staticandonce_cellcrates did. OnceLock::get_or_initblocks other threads until the first initializer finishes, so it runs at most once even under contention.LazyCellandLazyLockhave noget_mutand no reset: once built, the value stays.- Unlike
CellandRefCell, you can borrow a&Tout of aOnceCellfor as long as the cell lives, because the contents never change after initialization.
Related
- Cell, RefCell, Rc
- Tutorial: Thread-local and lazy values, RefCell and Cell