当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust SyncOnceCell.get_or_try_init用法及代码示例


本文简要介绍rust语言中 std::lazy::SyncOnceCell.get_or_try_init 的用法。

用法

pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E> where    F: FnOnce() -> Result<T, E>,

获取单元格的内容,如果单元格为空,则使用 f 对其进行初始化。如果单元格为空且f 失败,则返回错误。

Panics

如果 f 出现Panics,则Panics会传播给调用者,并且单元格保持未初始化状态。

f 重新初始化单元格是错误的。确切的结果是未指定的。当前的实现死锁,但将来可能会变成Panics。

例子

#![feature(once_cell)]

use std::lazy::SyncOnceCell;

let cell = SyncOnceCell::new();
assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
assert!(cell.get().is_none());
let value = cell.get_or_try_init(|| -> Result<i32, ()> {
    Ok(92)
});
assert_eq!(value, Ok(&92));
assert_eq!(cell.get(), Some(&92))

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 std::lazy::SyncOnceCell.get_or_try_init。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。