• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..--

.github/workflows/23-Nov-2023-2823

examples/23-Nov-2023-262199

src/23-Nov-2023-1,868856

tests/23-Nov-2023-871747

.cargo_vcs_info.jsonD23-Nov-202374 65

.gitignoreD23-Nov-202328 43

Android.bpD23-Nov-20231.9 KiB5955

CHANGELOG.mdD23-Nov-20234.1 KiB15295

Cargo.tomlD23-Nov-20231.8 KiB7563

Cargo.toml.origD23-Nov-20231.7 KiB7458

LICENSED23-Nov-202310.6 KiB202169

LICENSE-APACHED23-Nov-202310.6 KiB202169

LICENSE-MITD23-Nov-20231,023 2421

METADATAD23-Nov-2023383 2019

MODULE_LICENSE_APACHE2D23-Nov-20230

NOTICED23-Nov-202310.6 KiB202169

OWNERSD23-Nov-202340 21

README.mdD23-Nov-20232 KiB5742

TEST_MAPPINGD23-Nov-20231.3 KiB6766

bors.tomlD23-Nov-202350 32

cargo2android.jsonD23-Nov-2023195 1111

README.md

1<p align="center"><img src="design/logo.png" alt="once_cell"></p>
2
3
4[![Build Status](https://travis-ci.org/matklad/once_cell.svg?branch=master)](https://travis-ci.org/matklad/once_cell)
5[![Crates.io](https://img.shields.io/crates/v/once_cell.svg)](https://crates.io/crates/once_cell)
6[![API reference](https://docs.rs/once_cell/badge.svg)](https://docs.rs/once_cell/)
7
8# Overview
9
10`once_cell` provides two new cell-like types, `unsync::OnceCell` and `sync::OnceCell`. `OnceCell`
11might store arbitrary non-`Copy` types, can be assigned to at most once and provide direct access
12to the stored contents. In a nutshell, API looks *roughly* like this:
13
14```rust
15impl OnceCell<T> {
16    fn new() -> OnceCell<T> { ... }
17    fn set(&self, value: T) -> Result<(), T> { ... }
18    fn get(&self) -> Option<&T> { ... }
19}
20```
21
22Note that, like with `RefCell` and `Mutex`, the `set` method requires only a shared reference.
23Because of the single assignment restriction `get` can return an `&T` instead of `Ref<T>`
24or `MutexGuard<T>`.
25
26`once_cell` also has a `Lazy<T>` type, build on top of `OnceCell` which provides the same API as
27the `lazy_static!` macro, but without using any macros:
28
29```rust
30use std::{sync::Mutex, collections::HashMap};
31use once_cell::sync::Lazy;
32
33static 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
40fn main() {
41    println!("{:?}", GLOBAL_DATA.lock().unwrap());
42}
43```
44
45More 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
55The API of `once_cell` is being proposed for inclusion in
56[`std`](https://github.com/rust-lang/rfcs/pull/2788).
57