skip to content

In Rust, how does `std::cell::OnceCell` let you fill a value once through a shared reference, and what do `get`, `set` and `get_or_init` return?

level: juniorimportance: should knowfreq 40%

answer

  1. write once, read many
  2. shared reference, no RefCell checks
  3. Option, Result, plain reference
  4. Err hands the value back

basics

~20 s

OnceCell<T>, stable since Rust 1.70, starts empty and can be written exactly once through &self. get returns Option<&T>, get_or_init runs its closure only while the cell is empty and returns &T, and set returns Err(value) if a value is already stored.

solid answer

~40 s

`OnceCell<T>` (in `std::cell`, stable since Rust 1.70) is a slot that starts empty and accepts one write through a shared `&self`, after which it only hands out `&T`. `get()` returns `Option<&T>`: `None` until the cell is written. `get_or_init(f)` returns `&T`, calling `f` only if the cell is still empty, so a method on `&self` can load a settings file the first time it is asked and reuse the text afterwards. `set(value)` returns `Result<(), T>`: `Ok(())` on the first write and `Err(value)` afterwards, handing the rejected value back rather than overwriting. Because it never gives out `&mut T` through `&self`, it needs no runtime borrow counter like `RefCell`; changing the value again requires `&mut self` (`get_mut`, `take`). It is not `Sync`, so it is for one thread; `std::sync::OnceLock` is the thread-safe version.

code

rust · 23 lines
rust
use std::cell::OnceCell;

struct Config {
    path: String,
    text: OnceCell<String>,
}

impl Config {
    fn text(&self) -> &str {
        self.text.get_or_init(|| {
            println!("reading {}", self.path);
            format!("loaded from {}", self.path) // stands in for fs::read_to_string
        })
    }
}

fn main() {
    let cfg = Config { path: "app.toml".into(), text: OnceCell::new() };
    println!("{:?}", cfg.text.get());
    println!("{}", cfg.text());
    println!("{}", cfg.text());
    println!("{:?}", cfg.text.set(String::from("other")));
}

go deeper

for a junior

Recall the three signatures: get gives Option<&T>, get_or_init gives &T and runs the closure only once, set gives Err(value) when the cell is already full.

for a middle

Explain why a write-once cell can hand out &T through &self with no borrow counter, and contrast it with Cell and RefCell, which allow repeated mutation.

for a senior

Show when OnceCell beats LazyCell: the initialiser needs caller-side data. Mention that a panicking initialiser leaves the cell empty and that reentrant initialisation panics.

for a principal

Frame OnceCell as the single-threaded member of a four-type family and point out that choosing it documents that the value never crosses threads; the compiler enforces that through !Sync.

## What problem `OnceCell` solves Rust normally ties mutation to `&mut`: if you only hold a shared reference `&self`, you cannot write into a field. That is awkward for a value that is **expensive to compute and never changes once computed**, such as the contents of a settings file that a `Config` object should read only when someone first asks for it. `std::cell::OnceCell<T>` (stable since **Rust 1.70**, defined in `core::cell` and re-exported from `std::cell`) is the std answer: a cell that starts **empty**, can be written **once** through `&self`, and from then on hands out shared `&T` references to the stored value. The std documentation calls it "a cell which can nominally be written to only once". Its key property is that it can give out a plain `&T` **without copying or replacing** the value (unlike `Cell`) and **without runtime borrow checks** (unlike `RefCell`). That works because the stored value never changes while shared references to it exist: once written, it is read-only through `&self`. ## The three methods and what they return | Method | Receiver | Returns | Behaviour | |---|---|---|---| | `get` | `&self` | `Option<&T>` | `None` while empty, `Some(&value)` once written | | `set` | `&self` | `Result<(), T>` | `Ok(())` on the first write; `Err(value)` if already full, giving the value back | | `get_or_init` | `&self` | `&T` | runs the closure only if empty, stores the result, returns a reference | A few details worth stating precisely: - **`get_or_init` runs the closure at most once per successful initialisation.** On every later call the closure is not called at all; you just get the stored reference. - **`set` never overwrites.** The `Err` variant carries the rejected `T`, so nothing is silently dropped and the caller can decide what to do with it. - **`new` is a `const fn`**, so a `OnceCell` can be built in a constant context, although a plain `OnceCell` cannot sit in a `static` (see below). - **Mutation after the first write needs `&mut self`**: `get_mut` returns `Option<&mut T>`, `take` empties the cell and returns `Option<T>`, and `into_inner` consumes it. Those are only available when you own the cell exclusively, which is exactly when no shared `&T` can be outstanding. ## A lazily loaded settings field The typical use is a struct field that is filled on first access: 1. Declare the field as `OnceCell<String>` and construct it with `OnceCell::new()`. 2. Write an accessor on `&self` that calls `self.text.get_or_init(|| ...)` with the loading code inside the closure. 3. Return the `&str` it gives you; every caller after the first gets the cached text. The closure can borrow other fields of `self` (the file path, for instance), because `get_or_init` only needs `&self`. The code example below prints `reading app.toml` once even though the accessor is called twice, and a later `set` returns `Err("other")`. ## How it differs from its neighbours - **Versus `Cell<T>` and `RefCell<T>`:** those allow repeated mutation through `&self`; `Cell` by moving values in and out, `RefCell` by counting borrows at run time and panicking on a conflict. `OnceCell` allows only the first write, so it needs neither copying nor a borrow counter. - **Versus `std::sync::OnceLock<T>`:** same API, but `OnceLock` synchronises the first write between threads and is `Sync` when `T: Send + Sync`. `OnceCell` carries an explicit `!Sync` impl, so putting it in a `static` fails with **E0277** and rustc suggests `OnceLock`. - **Versus `LazyCell<T>`:** `LazyCell` (Rust 1.80) stores the initialising closure at construction and runs it on first dereference. `OnceCell` takes the closure at the call site, which is more flexible when the initialiser needs arguments that only the caller has. ## Edge cases - If the `get_or_init` closure **panics**, the panic propagates and the cell **stays empty**, so a later call can try again. - Calling `get_or_init` on the same cell **from inside its own closure** is a reentrant initialisation, which std documents as an error: for `OnceCell` it panics with the message `reentrant init`. - `get_or_try_init`, which would let the closure return a `Result`, is still **unstable** on std as of 1.99 (it exists in the `once_cell` crate). ## Why interviewers ask it The question checks whether a candidate knows that std, since 1.70, has a dedicated write-once cell, can read its signatures without guessing (`Option<&T>`, `Result<(), T>`, `&T`), and understands why it can hand out `&T` without `RefCell`'s runtime checks.

  • How do you replace the value in a `OnceCell` after it has been written?
    Only with exclusive access. `take(&mut self)` empties the cell and returns `Option<T>`, after which `set` or `get_or_init` can fill it again; `get_mut` gives `&mut T` to edit in place. Through `&self` there is no way to overwrite, which is what makes handing out plain `&T` sound.
  • Why can `OnceCell` return `&T` from `&self` without `RefCell`'s runtime borrow count?
    Because the stored value is never mutated through `&self`. The only write through a shared reference is the first one, into an empty cell that no `&T` can point at yet; after that, `&self` methods only read. Any later mutation requires `&mut self`, which the compiler already guarantees is exclusive.

A guest book page reserved for the first visitor's signature: anyone may read it, the first person to arrive signs it, and later visitors are handed their pen back instead of signing over it.

  • OnceCell set overwrites the stored value and returns Ok
  • get_or_init runs its closure on every call
  • OnceCell needs a mut binding because it mutates
  • OnceCell can be used directly in a static
  • get on an empty OnceCell returns a default value

Assumes Rust 1.99 on the 2024 edition; OnceCell and OnceLock are stable since 1.70 and LazyCell and LazyLock since 1.80, so older toolchains need the once_cell crate.