pub struct OnceCell<T> { /* private fields */ }
Expand description

A cell which can be written to only once.

This allows initialization using an async closure that borrows from its environment.

Unlike OnceFuture, the initialing closures do not require Send + 'static bounds.

use std::rc::Rc;
use std::sync::Arc;
use async_once_cell::OnceCell;

let non_send_value = Rc::new(4);
let shared = Arc::new(OnceCell::new());

let value : &i32 = shared.get_or_init(async {
    *non_send_value
}).await;
assert_eq!(value, &4);

// A second init is not called
let second = shared.get_or_init(async {
    unreachable!()
}).await;
assert_eq!(second, &4);

Implementations

Creates a new empty cell.

Creates a new cell with the given contents.

Gets the contents of the cell, initializing it with init if the cell was empty.

Many tasks may call get_or_init concurrently with different initializing futures, but it is guaranteed that only one future will be executed as long as the resuting future is polled to completion.

If init panics, the panic is propagated to the caller, and the cell remains uninitialized.

If the Future returned by this function is dropped prior to completion, the cell remains uninitialized (and another init futures may be selected for polling).

It is an error to reentrantly initialize the cell from init. The current implementation deadlocks, but will recover if the offending task is dropped.

Gets the contents of the cell, initializing it with init if the cell was empty. If the cell was empty and init failed, an error is returned.

If init panics, the panic is propagated to the caller, and the cell remains uninitialized.

If the Future returned by this function is dropped prior to completion, the cell remains uninitialized.

It is an error to reentrantly initialize the cell from init. The current implementation deadlocks, but will recover if the offending task is dropped.

Gets the reference to the underlying value.

Returns None if the cell is empty or being initialized. This method never blocks.

Gets a mutable reference to the underlying value.

Takes the value out of this OnceCell, moving it back to an uninitialized state.

Consumes the OnceCell, returning the wrapped value. Returns None if the cell was empty.

Trait Implementations

Formats the value using the given formatter. Read more

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.