pub struct OnceLock<T> { /* private fields */ }
Expand description
A synchronization primitive which can be used to run initialization code once. This type is thread safe and can be used in statics. All functions that can block are async.
Implementations§
Source§impl<T> OnceLock<T>
impl<T> OnceLock<T>
Sourcepub fn get(&self) -> Option<&T>
pub fn get(&self) -> Option<&T>
Get a reference to the data in the OnceLock
if it has been initialized.
Sourcepub fn get_mut(&mut self) -> Option<&mut T>
pub fn get_mut(&mut self) -> Option<&mut T>
Get a mutable reference to the data in the OnceLock
if it has been initialized.
Sourcepub fn into_inner(self) -> Option<T>
pub fn into_inner(self) -> Option<T>
Consumes the OnceLock
and returns the inner data if it has been initialized.
Sourcepub fn try_insert(&self, data: T) -> Result<&T, (&T, T)>
pub fn try_insert(&self, data: T) -> Result<&T, (&T, T)>
Attempt to set the data in the OnceLock
if it has not been initialized.
This is similar to OnceLock::set
but always returns the data in the OnceLock
.
§Errors
If the data in this OnceLock
is already initialized, the function returns
a reference to the previously stored data along with the value given as the
data
parameter.
Sourcepub async fn get_or_init(&self, init: impl FnOnce() -> T) -> &T
pub async fn get_or_init(&self, init: impl FnOnce() -> T) -> &T
Get or initialize the data in the OnceLock
.
This function will always return the value stored.
Sourcepub async fn get_or_try_init<E: Error>(
&self,
init: impl FnOnce() -> Result<T, E>,
) -> Result<&T, E>
pub async fn get_or_try_init<E: Error>( &self, init: impl FnOnce() -> Result<T, E>, ) -> Result<&T, E>
Get or try to initialize the data in the OnceLock
.
If the data in the OnceLock
is uninitialized, the init
function is run and
a reference to the newly created data is returned.
Otherwise, a reference to the previously stored data is returned.
§Errors
If init
is called and returns an error, the error is propagated and no value is set.