expression
Initialize async shared state once
Initialize a cell asynchronously and reuse the stored value. The successful initialization is retained, while a cancelled or panicking initializer can leave the cell uninitialized. Avoid recursive initialization of the same cell. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): 7 7 Common mistake: Assuming each caller’s initializer executes or recursively initializing the same cell.
Formal Syntax & Structure
rust syntaxrust
cell.get_or_init(|| async { value }).awaitWorking Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { let cell = tokio::sync::OnceCell::new(); let a = cell.get_or_init(|| async { 7 }).await; let b = cell.get_or_init(|| async { 99 }).await; println!("{a} {b}");}