#lazy #static

once_cell

Single assignment cells and lazy values

33 releases (15 stable)

new 1.8.0 Jun 13, 2021
1.7.2 Mar 2, 2021
1.5.2 Nov 12, 2020
1.4.0 May 13, 2020
0.1.6 Sep 21, 2018

#8 in Rust patterns

Download history 462665/week @ 2021-02-24 452329/week @ 2021-03-03 428675/week @ 2021-03-10 402317/week @ 2021-03-17 428126/week @ 2021-03-24 385655/week @ 2021-03-31 427233/week @ 2021-04-07 416433/week @ 2021-04-14 405272/week @ 2021-04-21 404931/week @ 2021-04-28 404614/week @ 2021-05-05 409229/week @ 2021-05-12 391144/week @ 2021-05-19 387478/week @ 2021-05-26 388046/week @ 2021-06-02 364208/week @ 2021-06-09

1,725,889 downloads per month
Used in 8,128 crates (860 directly)

MIT/Apache

67KB
870 lines

once_cell

Build Status Crates.io API reference

Overview

once_cell provides two new cell-like types, unsync::OnceCell and sync::OnceCell. OnceCell might store arbitrary non-Copy types, can be assigned to at most once and provide direct access to the stored contents. In a nutshell, API looks roughly like this:

impl OnceCell<T> {
    fn new() -> OnceCell<T> { ... }
    fn set(&self, value: T) -> Result<(), T> { ... }
    fn get(&self) -> Option<&T> { ... }
}

Note that, like with RefCell and Mutex, the set method requires only a shared reference. Because of the single assignment restriction get can return an &T instead of Ref<T> or MutexGuard<T>.

once_cell also has a Lazy<T> type, build on top of OnceCell which provides the same API as the lazy_static! macro, but without using any macros:

use std::{sync::Mutex, collections::HashMap};
use once_cell::sync::Lazy;

static GLOBAL_DATA: Lazy<Mutex<HashMap<i32, String>>> = Lazy::new(|| {
    let mut m = HashMap::new();
    m.insert(13, "Spica".to_string());
    m.insert(74, "Hoyten".to_string());
    Mutex::new(m)
});

fn main() {
    println!("{:?}", GLOBAL_DATA.lock().unwrap());
}

More patterns and use-cases are in the docs!

Related crates

The API of once_cell is being proposed for inclusion in std.

Dependencies

~130KB