跳到主要内容

SetOnce

搜索

结构体 SetOnce 

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

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

SetOnce 的灵感 来自 python 的 asyncio.Event 类型。 它 可用于 等待 直到 SetOnce 的值 被设置, 类似于 “Event” 机制。

§Example

use tokio::sync::{SetOnce, SetOnceError};







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











// set the value inside a task somewhere...



tokio::spawn(async move { ONCE.set(20) });







// checking with .get doesn't block main thread



println!("{:?}", ONCE.get());







// wait until the value is set, blocks the thread



println!("{:?}", ONCE.wait().await);







Ok(())

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

§Example

use tokio::sync::{SetOnce, SetOnceError};



use std::sync::Arc;







let once = SetOnce::new();







let arc = Arc::new(once);



let first_cl = Arc::clone(&arc);



let second_cl = Arc::clone(&arc);







// set the value inside a task



tokio::spawn(async move { first_cl.set(20) }).await.unwrap()?;







// wait inside task to not block the main thread



tokio::spawn(async move {



    // wait inside async context for the value to be set



    assert_eq!(*second_cl.wait().await, 20);



}).await.unwrap();







// subsequent set calls will fail



assert!(arc.set(30).is_err());







println!("{:?}", arc.get());







Ok(())

实现§

Source§

impl<T> SetOnce<T>

Source

pub fn new() -> Self

创建一个新的空 SetOnce 实例。

Source

pub const fn const_new() -> Self

创建一个新的空 SetOnce 实例。

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

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

§Example
use tokio::sync::{SetOnce, SetOnceError};







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







fn get_global_integer() -> Result<Option<&'static u32>, SetOnceError<u32>> {



    ONCE.set(2)?;



    Ok(ONCE.get())



}







let result = get_global_integer()?;







assert_eq!(result, Some(&2));



Ok(())
Source

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

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

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

Source

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

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

§Example

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

use tokio::sync::SetOnce;







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







fn get_global_integer() -> Option<&'static u32> {



    ONCE.get()



}







let result = get_global_integer();







assert_eq!(result, Some(&1));
Source

pub fn initialized(&self) -> bool

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

Source

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

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

Source

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

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

如果 SetOnce 已有值,此调用将失败并返回 SetOnceError

Source

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

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

Source

pub async fn wait(&self) -> &T

等待值被设置。

如果 SetOnce 已经被初始化,它会立即返回值。

§Cancel safety

此方法是取消安全的。

Trait 实现§

Source§

impl<T: Clone> Clone for SetOnce<T>

Source§

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

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

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

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

impl<T: Debug> Debug for SetOnce<T>

Source§

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

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

impl<T> Default for SetOnce<T>

Source§

fn default() -> SetOnce<T>

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

impl<T> Drop for SetOnce<T>

Source§

fn drop(&mut self)

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

impl<T> From<T> for SetOnce<T>

Source§

fn from(value: T) -> Self

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

impl<T: PartialEq> PartialEq for SetOnce<T>

Source§

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

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

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

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

impl<T: Eq> Eq for SetOnce<T>

Source§

impl<T: Send> Send for SetOnce<T>

Source§

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

自动 Trait 实现§

§

impl<T> !Freeze for SetOnce<T>

§

impl<T> !RefUnwindSafe for SetOnce<T>

§

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

§

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

§

impl<T> UnwindSafe for SetOnce<T>
where T: UnwindSafe,

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>

执行转换。