std-method

Rust OnceCell::get_or_init

Compute a value on demand, store it after successful initialization and reuse it on subsequent calls. An initializer panic leaves OnceCell uninitialized; recursive initialization is invalid. Avoid reentering the same cell. Expected output (not executed): index index 1 Why: The closure captures a shared reference to calls; only the first access initializes. Common mistake: Using this cache for data that must refresh after every input change.

Formal Syntax & Structure

rust syntaxrust
cell.get_or_init(|| value) -> &T

Working Example

Example Snippetrust
use std::cell::{Cell, OnceCell};fn main() {    let calls = Cell::new(0);    let cache = OnceCell::new();    let build = || { calls.set(calls.get() + 1); String::from("index") };    println!("{} {}", cache.get_or_init(build), cache.get_or_init(build));    println!("{}", calls.get());}
Rust Reference