pub struct OnceCell<T> { /* private fields */ }
Expand description
Cell which can be lazy instantiated with an asynchronous block and is safely share-able between threads.
Implementations§
Source§impl<T> OnceCell<T>
impl<T> OnceCell<T>
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new empty OnceCell. Currently this function is not const due to Mutex limitations, so to share between multiple threads an Arc needs to be used.
Sourcepub async fn get_or_init<F>(&self, f: F) -> &Twhere
F: Future<Output = T>,
pub async fn get_or_init<F>(&self, f: F) -> &Twhere
F: Future<Output = T>,
Get or initialize this cell with the given asynchronous block. If the cell is already initialized, the current value will be returned. Otherwise the asynchronous block is used to initialize the OnceCell. This function will always return a value.
§Example
let cell = OnceCell::new();
cell.get_or_init(async {
0 // expensive calculation
}).await;
assert_eq!(cell.get(), Some(&0));
Sourcepub async fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
pub async fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
Get or initialize this cell with the given asynchronous block. If the cell is already initialized, the current value will be returned. Otherwise the asynchronous block is used to initialize the OnceCell. This function will always return a value.
§Example
let cell = OnceCell::new();
cell.get_or_try_init(async {
Ok::<_, Infallible>(0) // expensive calculation
}).await;
assert_eq!(cell.get(), Some(&0));
Sourcepub fn get(&self) -> Option<&T>
pub fn get(&self) -> Option<&T>
Returns the value of the OnceCell or None if the OnceCell has not been initialized yet.
Sourcepub fn initialized(&self) -> bool
pub fn initialized(&self) -> bool
If the OnceCell is already initialized, either by having have called get_or_init()
or get_or_try_init()
.