pub struct LazyCell<T, F = fn() -> T> { /* private fields */ }
🔬This is a nightly-only experimental API. (
lazy_cell
#109736)Expand description
在首次访问时初始化的值。
有关此结构体的线程安全版本,请参见 std::sync::LazyLock
。
Examples
#![feature(lazy_cell)]
use std::cell::LazyCell;
let lazy: LazyCell<i32> = LazyCell::new(|| {
println!("initializing");
92
});
println!("ready");
println!("{}", *lazy);
println!("{}", *lazy);
// Prints:
// 准备初始化
// 92
// 92
RunImplementations§
source§impl<T, F> LazyCell<T, F>where
F: FnOnce() -> T,
impl<T, F> LazyCell<T, F>where F: FnOnce() -> T,
sourcepub const fn new(f: F) -> LazyCell<T, F>
🔬This is a nightly-only experimental API. (lazy_cell
#109736)
pub const fn new(f: F) -> LazyCell<T, F>
lazy_cell
#109736)sourcepub fn into_inner(this: LazyCell<T, F>) -> Result<T, F>
🔬This is a nightly-only experimental API. (lazy_cell_consume
#109736)
pub fn into_inner(this: LazyCell<T, F>) -> Result<T, F>
lazy_cell_consume
#109736)使用此 LazyCell
返回存储的值。
如果 Lazy
已初始化,则返回 Ok(value)
,否则返回 Err(f)
。
Examples
#![feature(lazy_cell)]
#![feature(lazy_cell_consume)]
use std::cell::LazyCell;
let hello = "Hello, World!".to_string();
let lazy = LazyCell::new(|| hello.to_uppercase());
assert_eq!(&*lazy, "HELLO, WORLD!");
assert_eq!(LazyCell::into_inner(lazy).ok(), Some("HELLO, WORLD!".to_string()));
Run