跳到主要内容

SetOnce

搜索

结构体 SetOnce 

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

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

SetOnce 灵感来自 Python 的 asyncio.Event 类型。它可用于等待 SetOnce 的值被设置,类似于"事件"机制。

§示例

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 允许异步执行初始化过程。

§示例

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

实现§

源代码§

impl<T> SetOnce<T>

源代码

pub fn new() -> Self

创建一个新的空 SetOnce 实例。

源代码

pub const fn const_new() -> Self

创建一个新的空 SetOnce 实例。

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

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

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

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

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

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

源代码

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

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

§示例

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

pub fn initialized(&self) -> bool

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

源代码

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

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

源代码

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

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

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

源代码

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

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

源代码

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

等待直到值被设置。

如果 SetOnce 已初始化,它将立即返回值。

§取消安全性

此方法可安全取消。

trait 实现§

源代码§

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

源代码§

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

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

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

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

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

源代码§

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

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

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

源代码§

fn default() -> SetOnce<T>

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

impl<T> Drop for SetOnce<T>

源代码§

fn drop(&mut self)

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

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

源代码§

fn from(value: T) -> Self

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

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

源代码§

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

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

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

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

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

源代码§

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

源代码§

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 实现§

源代码§

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>

执行转换。