← 中文资源

简体中文版本

OnceCell 惰性初始化结构体字段

OnceCell 让 &self 方法在首次调用时算出派生值并缓存:get_or_init 只算一次,set 在已有值时返回 Err。

阅读英文原文

实现说明

除了函数 new、total、main,文件里再无其他定义。

使用要点

  • 演示输出是带标签的(first read:、cached read:、same value:),每个操作都会留下自己的一行标注。
  • main 的演示流程是 new、total——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「OnceCell 惰性初始化结构体字段」会打印什么?

运行文件本身,first read:、cached read:、same value: 这些前缀各对应一段演示逻辑。

入口签名:fn new(rows: Vec<u32>) -> Self

核心语句

fn new(rows: Vec<u32>) -> Self {
    Self { rows, total: OnceCell::new() }
}
fn total(&self) -> u32 {
    *self.total.get_or_init(|| self.rows.iter().sum())
}

代码示例

use std::cell::OnceCell;

struct Report {
    rows: Vec<u32>,
    // 只能通过 &self 初始化一次的派生值
    total: OnceCell<u32>,
}

impl Report {
    fn new(rows: Vec<u32>) -> Self {
        Self { rows, total: OnceCell::new() }
    }

    // 第一次调用计算并存入,之后每次调用直接返回缓存
    fn total(&self) -> u32 {
        *self.total.get_or_init(|| self.rows.iter().sum())
    }
}

fn main() {
    let report = Report::new(vec![3, 9, 1, 7]);
    println!("first read: {}", report.total());
    println!("cached read: {}", report.total());
    println!("same value: {}", report.total.get().copied() == Some(20));

    // 已初始化后不可改写:set 在有值时返回 Err
    let replaced = report.total.set(0);
    println!("set after init failed: {}", replaced.is_err());
}