API Reference

once_cell

Rust library for single-assignment cells and lazy statics with thread-safe initialization.

Official Documentation ↗
CompatibilityThis documentation covers version once_cell 1.20 / Rust 1.70+(std 已内置部分替代). Check the official docs for the latest API surface.

Installation

cargocargo add once_cell

Methods

Overview

once_cell provides cells that can be initialized once, plus lazy statics. They enable global configuration, compiled regexes and connection pools initialized safely without exposing mutable statics.

Core Methods

OnceCell and OnceLock hold a value set once; Lazy wraps a closure evaluated on first deref. get_or_init returns a reference after ensuring initialization, and try variants handle fallible setup.

Usage Notes

Use Lazy for static tables and regexes, OnceCell for dependency-injected singletons, and try variants when initialization can fail so the error can be handled.

Common Pitfalls

A panicking initializer leaves the cell uninitialized in some versions or poisons it, so keep initializers robust. Global state complicates testing, so keep lazy statics small and injectables injectable.

FAQ

What replaces once_cell in std?
OnceLock and LazyLock landed in the standard library, so new code can often use those instead of once_cell. once_cell remains useful for older toolchains and additional APIs.
Is initialization thread safe?
Yes, the sync variants serialize initialization so exactly one thread runs the initializer and others block or wait, preventing duplicate expensive work.
When should I use Lazy versus OnceCell?
Use Lazy for a value initialized on first use with a fixed closure, and OnceCell when initialization depends on runtime data or may fail.