跳到主要内容

OnceCell

搜索

结构体 OnceCell 

Source
pub struct OnceCell<T> { /* private fields */ }
展开描述

一个线程安全的 cell,只能写入一次。

OnceCell 通常用于 在首次使用时 需要 初始化一次, 但 不需要 进一步 更改的 全局变量。 Tokio 中的 OnceCell 允许 初始化过程 是异步的。

§示例

use tokio::sync::OnceCell;





async fn some_computation() -> u32 {


    1 + 1


}





static ONCE: OnceCell<u32> = OnceCell::const_new();





let result = ONCE.get_or_init(some_computation).await;


assert_eq!(*result, 2);

编写 一个包装方法 来 访问该值 通常 很有用。

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


}





let result = get_global_integer().await;


assert_eq!(*result, 2);

实现§

Source§

impl<T> OnceCell<T>

Source

pub fn new() -> Self

创建一个新的空 OnceCell 实例。

Source

pub const fn const_new() -> Self

创建一个新的空 OnceCell 实例。

OnceCell::new 等价,但可用于静态变量中。

使用 tracing 不稳定特性时,通过 const_new 创建的 OnceCell 不会被插桩。因此,它不会出现在 tokio-console 中。如有需要,请改用 OnceCell::new 来创建可插桩的对象。

§Example
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


}





let result = get_global_integer().await;


assert_eq!(*result, 2);
Source

pub fn new_with(value: Option<T>) -> Self

创建一个包含所提供值(如果有)的新的 OnceCell

如果 OptionNone,则等价于 OnceCell::new

Source

pub const fn const_new_with(value: T) -> Self

创建一个包含所提供值的新的 OnceCell

§Example

使用 tracing 不稳定特性时,通过 const_new_with 创建的 OnceCell 不会被插桩。因此,它不会出现在 tokio-console 中。如有需要,请改用 OnceCell::new_with 来创建可插桩的对象。

use tokio::sync::OnceCell;





static ONCE: OnceCell<u32> = OnceCell::const_new_with(1);





async fn get_global_integer() -> &'static u32 {


    ONCE.get_or_init(|| async {


        1 + 1


    }).await


}





let result = get_global_integer().await;


assert_eq!(*result, 1);
Source

pub fn initialized(&self) -> bool

如果 OnceCell 当前包含值则返回 true,否则返回 false

Source

pub fn get(&self) -> Option<&T>

返回当前存储在 OnceCell 中的值的引用,如果 OnceCell 为空则返回 None

Source

pub fn get_mut(&mut self) -> Option<&mut T>

返回当前存储在 OnceCell 中的值的可变引用,如果 OnceCell 为空则返回 None

由于此调用可变地借用 OnceCell,因此可以安全地修改 OnceCell 中的值 —— 可变借用静态保证不存在其他引用。

Source

pub fn set(&self, value: T) -> Result<(), SetError<T>>

如果 OnceCell 为空,则将其值设置为给定值。

如果 OnceCell 已有值,此调用将失败并返回 SetError::AlreadyInitializedError

如果 OnceCell 为空但其他任务当前正在尝试设置值,则此调用将失败并返回 SetError::InitializingError

Source

pub async fn get_or_init<F, Fut>(&self, f: F) -> &T
where F: FnOnce() -> Fut, Fut: Future<Output = T>,

获取 OnceCell 中当前的值,如果不存在则使用给定的异步操作进行初始化。

如果其他任务当前正在初始化该 OnceCell,则此调用将等待该任务完成,然后返回其产生的值。

如果提供的操作被取消或 panic,则取消初始化尝试。如果有其他任务正在等待值的初始化,其中一个将开始另一次初始化尝试。

如果 f 尝试递归地初始化此单元格,将会发生死锁。

Source

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>>,

获取 OnceCell 中当前的值,如果不存在则使用给定的异步操作进行初始化。

如果其他任务当前正在初始化该 OnceCell,则此调用将等待该任务完成,然后返回其产生的值。

如果提供的操作返回错误、被取消或 panic,则取消初始化尝试。如果有其他任务正在等待值的初始化,其中一个将开始另一次初始化尝试。

如果 f 尝试递归地初始化此单元格,将会发生死锁。

Source

pub fn into_inner(self) -> Option<T>

从单元格中取值,并在过程中销毁单元格。如果单元格为空则返回 None

Source

pub fn take(&mut self) -> Option<T>

获取当前值的所有权,使单元格留空。如果单元格为空则返回 None

Trait 实现§

Source§

impl<T: Clone> Clone for OnceCell<T>

Source§

fn clone(&self) -> OnceCell<T>

返回值的副本。 更多信息
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. 更多信息
Source§

impl<T: Debug> Debug for OnceCell<T>

Source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

使用给定的格式化器格式化此值。 更多信息
Source§

impl<T> Default for OnceCell<T>

Source§

fn default() -> OnceCell<T>

Returns the “default value” for a type. 更多信息
Source§

impl<T> Drop for OnceCell<T>

Source§

fn drop(&mut self)

执行此类型的析构函数。 更多信息
Source§

impl<T> From<T> for OnceCell<T>

Source§

fn from(value: T) -> Self

从输入类型转换为此类型。
Source§

impl<T: PartialEq> PartialEq for OnceCell<T>

Source§

fn eq(&self, other: &OnceCell<T>) -> bool

测试 selfother 值是否相等,供 == 运算符使用。
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

测试 != 运算符。默认实现几乎总是够用,除非有非常充分的理由,否则不应被覆盖。
Source§

impl<T: Eq> Eq for OnceCell<T>

Source§

impl<T: Send> Send for OnceCell<T>

Source§

impl<T: Sync + Send> Sync for OnceCell<T>

自动 Trait 实现§

§

impl<T> !Freeze for OnceCell<T>

§

impl<T> !RefUnwindSafe for OnceCell<T>

§

impl<T> Unpin for OnceCell<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for OnceCell<T>
where T: UnsafeUnpin,

§

impl<T> !UnwindSafe for OnceCell<T>

Blanket 实现§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. 更多信息
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 更多信息
Source§

impl<T> From<!> for T

Source§

fn from(t: !) -> T

从输入类型转换为此类型。
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

原样返回传入的参数。

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换的具体行为取决于 From<T> for U 的实现方式。

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

获得所有权后的类型。
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. 更多信息
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 更多信息
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

转换出错时返回的类型。
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

转换出错时返回的类型。
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

执行转换。