跳到主要内容

OnceCell

搜索

结构体 OnceCell 

源代码
pub struct OnceCell<T> { /* 私有字段 */ }
展开描述

只能写入一次的线程安全单元。

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);

实现§

源代码§

impl<T> OnceCell<T>

源代码

pub fn new() -> Self

创建一个新的空 OnceCell 实例。

源代码

pub const fn const_new() -> Self

创建一个新的空 OnceCell 实例。

等效于 OnceCell::new,但可以在静态变量中使用。

当使用 tracing 不稳定功能 时,使用 const_new 创建的 OnceCell 不会被检测。因此,它在 tokio-console 中不可见。如果需要,应改用 OnceCell::new 创建被检测的对象。

§示例
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);
源代码

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

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

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

源代码

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

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

§示例

当使用 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);
源代码

pub fn initialized(&self) -> bool

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

源代码

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

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

源代码

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

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

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

源代码

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

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

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

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

源代码

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

获取 OnceCell 中当前的值,或使用给定的异步操作进行初始化。

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

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

如果 f 尝试递归初始化单元,则会发生死锁。

源代码

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 尝试递归初始化单元,则会发生死锁。

源代码

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

从单元中取出值,此过程会销毁单元。如果单元为空,则返回 None

源代码

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

取得当前值的所有权,使 cell 留空。如果 cell 为空,则返回 None

trait 实现§

源代码§

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

源代码§

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

返回值的副本。 更多信息
1.0.0 · 源代码§

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

Performs copy-assignment from source. 更多信息
源代码§

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

源代码§

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

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

impl<T> 默认值 for OnceCell<T>

源代码§

fn default() -> OnceCell<T>

Returns the “default value” for a type. 更多信息
源代码§

impl<T> Drop for OnceCell<T>

源代码§

fn drop(&mut self)

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

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

源代码§

fn from(value: T) -> Self

从输入类型转换为此类型。
源代码§

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

源代码§

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

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

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

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

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

源代码§

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

源代码§

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>
where T: UnwindSafe,

blanket 实现§

源代码§

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

源代码§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
源代码§

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

源代码§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
源代码§

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

源代码§

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

Mutably borrows from an owned value. 更多信息
源代码§

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

源代码§

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. 更多信息
源代码§

impl<T> From<!> for T

源代码§

fn from(t: !) -> T

从输入类型转换为此类型。
源代码§

impl<T> From<T> for T

源代码§

fn from(t: T) -> T

原样返回参数。

源代码§

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

源代码§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换是 From<T> for U 实现选择执行的操作。

源代码§

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

源代码§

type Owned = T

获得所有权后的类型。
源代码§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. 更多信息
源代码§

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

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

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

源代码§

type Error = Infallible

转换出错时返回的类型。
源代码§

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

执行转换。
源代码§

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

源代码§

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

转换出错时返回的类型。
源代码§

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

执行转换。