pub struct OnceCell<T> { /* private fields */ }
Expand description
A thread-safe cell that can be written to only once.
A OnceCell
is typically used for global variables that need to be
initialized once on first use, but need no further changes. The OnceCell
in Tokio allows the initialization procedure to be asynchronous.
Examples
use tokio::sync::OnceCell;
async fn some_computation() -> u32 {
1 + 1
}
static ONCE: OnceCell<u32> = OnceCell::const_new();
#[tokio::main]
async fn main() {
let result = ONCE.get_or_init(some_computation).await;
assert_eq!(*result, 2);
}
It is often useful to write a wrapper method for accessing the value.
use tokio::sync::OnceCell;
static ONCE: OnceCell<u32> = OnceCell::const_new();
async fn get_global_integer() -> &'static u32 {
ONCE.get_or_init(|| async {
1 + 1
}).await
}
#[tokio::main]
async fn main() {
let result = get_global_integer().await;
assert_eq!(*result, 2);
}
Implementations
impl<T> OnceCell<T>
impl<T> OnceCell<T>
pub fn new_with(value: Option<T>) -> OnceCell<T>
pub fn new_with(value: Option<T>) -> OnceCell<T>
Creates a new OnceCell
that contains the provided value, if any.
If the Option
is None
, this is equivalent to OnceCell::new
.
pub fn initialized(&self) -> bool
pub fn initialized(&self) -> bool
Returns true
if the OnceCell
currently contains a value, and false
otherwise.
pub fn get(&self) -> Option<&T>
pub fn get(&self) -> Option<&T>
Returns a reference to the value currently stored in the OnceCell
, or
None
if the OnceCell
is empty.
pub fn get_mut(&mut self) -> Option<&mut T>
pub fn get_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the value currently stored in the
OnceCell
, or None
if the OnceCell
is empty.
Since this call borrows the OnceCell
mutably, it is safe to mutate the
value inside the OnceCell
— the mutable borrow statically guarantees
no other references exist.
pub fn set(&self, value: T) -> Result<(), SetError<T>>
pub fn set(&self, value: T) -> Result<(), SetError<T>>
Sets the value of the OnceCell
to the given value if the OnceCell
is
empty.
If the OnceCell
already has a value, this call will fail with an
SetError::AlreadyInitializedError
.
If the OnceCell
is empty, but some other task is currently trying to
set the value, this call will fail with SetError::InitializingError
.
pub async fn get_or_init<F, Fut>(&'_ self, f: F) -> &'_ T where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
pub async fn get_or_init<F, Fut>(&'_ self, f: F) -> &'_ T where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
Gets the value currently in the OnceCell
, or initialize it with the
given asynchronous operation.
If some other task is currently working on initializing the OnceCell
,
this call will wait for that other task to finish, then return the value
that the other task produced.
If the provided operation is cancelled or panics, the initialization attempt is cancelled. If there are other tasks waiting for the value to be initialized, one of them will start another attempt at initializing the value.
This will deadlock if f
tries to initialize the cell recursively.
pub async fn get_or_try_init<E, F, Fut>(&'_ self, f: F) -> Result<&'_ T, E> where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T, E>>,
pub async fn get_or_try_init<E, F, Fut>(&'_ self, f: F) -> Result<&'_ T, E> where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T, E>>,
Gets the value currently in the OnceCell
, or initialize it with the
given asynchronous operation.
If some other task is currently working on initializing the OnceCell
,
this call will wait for that other task to finish, then return the value
that the other task produced.
If the provided operation returns an error, is cancelled or panics, the initialization attempt is cancelled. If there are other tasks waiting for the value to be initialized, one of them will start another attempt at initializing the value.
This will deadlock if f
tries to initialize the cell recursively.
pub fn into_inner(self) -> Option<T>
pub fn into_inner(self) -> Option<T>
Takes the value from the cell, destroying the cell in the process.
Returns None
if the cell is empty.
Trait Implementations
impl<T> Eq for OnceCell<T> where
T: Eq,
impl<T> Send for OnceCell<T> where
T: Send,
impl<T> Sync for OnceCell<T> where
T: Sync + Send,
Auto Trait Implementations
impl<T> !RefUnwindSafe for OnceCell<T>
impl<T> Unpin for OnceCell<T> where
T: Unpin,
impl<T> UnwindSafe for OnceCell<T> where
T: UnwindSafe,
Blanket Implementations
sourceimpl<D> AsyncTryClone for D where
D: Clone + Sync,
impl<D> AsyncTryClone for D where
D: Clone + Sync,
sourcefn async_try_clone<'life0, 'async_trait>(
&'life0 self
) -> Pin<Box<dyn Future<Output = Result<D, Error>> + Send + 'async_trait, Global>>ⓘNotable traits for Pin<P>impl<P> Future for Pin<P> where
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
where
'life0: 'async_trait,
D: 'async_trait,
fn async_try_clone<'life0, 'async_trait>(
&'life0 self
) -> Pin<Box<dyn Future<Output = Result<D, Error>> + Send + 'async_trait, Global>>ⓘNotable traits for Pin<P>impl<P> Future for Pin<P> where
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
where
'life0: 'async_trait,
D: 'async_trait,
P: DerefMut,
<P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output;
Try cloning a object and return an Err
in case of failure.
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
fn instrument(self, span: Span) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
T: Future, type Output = <T as Future>::Output;
sourcefn in_current_span(self) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
fn in_current_span(self) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
T: Future, type Output = <T as Future>::Output;
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
where
S: Into<Dispatch>,
T: Future, type Output = <T as Future>::Output;
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
fn with_current_subscriber(self) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
T: Future, type Output = <T as Future>::Output;
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more