std-type

Rust LazyCell<T, F>

LazyCell stores an initialization function along with a value that is computed upon first access. It is suited to single-threaded deferred initialization. Unlike OnceCell, a panicking initializer poisons LazyCell; later accesses panic too. Expected output (not executed): before build 2 3 Why: The first dereference invokes the initializer, and later access reuses its result. Common mistake: Expecting the initializer to run at construction time.

Formal Syntax & Structure

rust syntaxrust
LazyCell::new(|| value)

Working Example

Example Snippetrust
use std::cell::LazyCell;fn main() {    let report = LazyCell::new(|| { println!("build"); vec![3, 4] });    println!("before");    println!("{}", report.len());    println!("{}", report[0]);}
Rust Reference