Struct core::lazy::OnceCell [−][src]
pub struct OnceCell<T> { /* fields omitted */ }
Expand description
一个 cell 只能写入一次。
与 RefCell
不同,OnceCell
仅为其值提供共享的 &T
引用。
与 Cell
不同,OnceCell
不需要复制或替换值即可访问它。
Examples
#![feature(once_cell)]
use std::lazy::OnceCell;
let cell = OnceCell::new();
assert!(cell.get().is_none());
let value: &String = cell.get_or_init(|| {
"Hello, World!".to_string()
});
assert_eq!(value, "Hello, World!");
assert!(cell.get().is_some());
RunImplementations
创建一个新的空 cell。
获取对底层值的引用。
如果 cell 为空,则返回 None
。
获取对底层值的可变引用。
如果 cell 为空,则返回 None
。
获取 cell 的内容,如果 cell 为空,则使用 f
对其进行初始化。
Panics
如果 f
panics,则 panic 会传播给调用者,并且 cell 仍保持未初始化状态。
重新从 f
初始化 cell 是错误的。这样做会导致 panic。
Examples
#![feature(once_cell)]
use std::lazy::OnceCell;
let cell = OnceCell::new();
let value = cell.get_or_init(|| 92);
assert_eq!(value, &92);
let value = cell.get_or_init(|| unreachable!());
assert_eq!(value, &92);
Run获取 cell 的内容,如果 cell 为空,则使用 f
对其进行初始化。
如果 cell 为空并且 f
失败,则返回错误。
Panics
如果 f
panics,则 panic 会传播给调用者,并且 cell 仍保持未初始化状态。
重新从 f
初始化 cell 是错误的。这样做会导致 panic。
Examples
#![feature(once_cell)]
use std::lazy::OnceCell;
let cell = OnceCell::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))
Run消费 cell,返回包装后的值。
如果 cell 为空,则返回 None
。
Examples
#![feature(once_cell)]
use std::lazy::OnceCell;
let cell: OnceCell<String> = OnceCell::new();
assert_eq!(cell.into_inner(), None);
let cell = OnceCell::new();
cell.set("hello".to_string()).unwrap();
assert_eq!(cell.into_inner(), Some("hello".to_string()));
Run从 OnceCell
中取出值,将其移回未初始化状态。
无效,如果尚未初始化 OnceCell
,则返回 None
。
通过要求可变引用来保证安全。
Examples
#![feature(once_cell)]
use std::lazy::OnceCell;
let mut cell: OnceCell<String> = OnceCell::new();
assert_eq!(cell.take(), None);
let mut cell = OnceCell::new();
cell.set("hello".to_string()).unwrap();
assert_eq!(cell.take(), Some("hello".to_string()));
assert_eq!(cell.get(), None);
Run