| 1 |
<p align="center"><img src="design/logo.png" alt="once_cell"></p> |
| 2 |
|
| 3 |
|
| 4 |
[](https://github.com/matklad/once_cell/actions) |
| 5 |
[](https://crates.io/crates/once_cell) |
| 6 |
[](https://docs.rs/once_cell/) |
| 7 |
|
| 8 |
# Overview |
| 9 |
|
| 10 |
`once_cell` provides two new cell-like types, `unsync::OnceCell` and `sync::OnceCell`. `OnceCell` |
| 11 |
might store arbitrary non-`Copy` types, can be assigned to at most once and provide direct access |
| 12 |
to the stored contents. In a nutshell, API looks *roughly* like this: |
| 13 |
|
| 14 |
```rust |
| 15 |
impl OnceCell<T> { |
| 16 |
fn new() -> OnceCell<T> { ... } |
| 17 |
fn set(&self, value: T) -> Result<(), T> { ... } |
| 18 |
fn get(&self) -> Option<&T> { ... } |
| 19 |
} |
| 20 |
``` |
| 21 |
|
| 22 |
Note that, like with `RefCell` and `Mutex`, the `set` method requires only a shared reference. |
| 23 |
Because of the single assignment restriction `get` can return an `&T` instead of `Ref<T>` |
| 24 |
or `MutexGuard<T>`. |
| 25 |
|
| 26 |
`once_cell` also has a `Lazy<T>` type, build on top of `OnceCell` which provides the same API as |
| 27 |
the `lazy_static!` macro, but without using any macros: |
| 28 |
|
| 29 |
```rust |
| 30 |
use std::{sync::Mutex, collections::HashMap}; |
| 31 |
use once_cell::sync::Lazy; |
| 32 |
|
| 33 |
static GLOBAL_DATA: Lazy<Mutex<HashMap<i32, String>>> = Lazy::new(|| { |
| 34 |
let mut m = HashMap::new(); |
| 35 |
m.insert(13, "Spica".to_string()); |
| 36 |
m.insert(74, "Hoyten".to_string()); |
| 37 |
Mutex::new(m) |
| 38 |
}); |
| 39 |
|
| 40 |
fn main() { |
| 41 |
println!("{:?}", GLOBAL_DATA.lock().unwrap()); |
| 42 |
} |
| 43 |
``` |
| 44 |
|
| 45 |
More patterns and use-cases are in the [docs](https://docs.rs/once_cell/)! |
| 46 |
|
| 47 |
# Related crates |
| 48 |
|
| 49 |
* [double-checked-cell](https://github.com/niklasf/double-checked-cell) |
| 50 |
* [lazy-init](https://crates.io/crates/lazy-init) |
| 51 |
* [lazycell](https://crates.io/crates/lazycell) |
| 52 |
* [mitochondria](https://crates.io/crates/mitochondria) |
| 53 |
* [lazy_static](https://crates.io/crates/lazy_static) |
| 54 |
* [async_once_cell](https://crates.io/crates/async_once_cell) |
| 55 |
* [generic_once_cell](https://crates.io/crates/generic_once_cell) (bring your own mutex) |
| 56 |
|
| 57 |
Parts of `once_cell` API are included into `std` [as of Rust 1.70.0](https://github.com/rust-lang/rust/pull/105587). |