OnceCell Lazily Initializes Struct Fields

Cache a derived value inside a struct with OnceCell: get_or_init computes once under &self, later reads reuse it, and set after init errors.

RustData Integrity

Code

rustsnippet
29 lines
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());
}

How it works

Count the functions new, total and main as the entire surface area of OnceCell Lazily Initializes Struct Fields.

Using it

The main signature reads fn new(rows: Vec<u32>) -> Self

The demo output is labeled (first read:, cached read:, same value:), so every printed line maps back to its originating operation.

Treat main as the orchestrator calling new and total in a fixed order.

Key statements

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

Interactive Tools for This Topic

FAQ

What does OnceCell Lazily Initializes Struct Fields print when run?
Execute the whole file; each printed line is prefixed with a label like `first read:`, `cached read:`, `same value:`.