25 releases (8 stable)

1.4.1 Aug 17, 2020
1.4.0 May 13, 2020
1.3.1 Jan 17, 2020
1.2.0 Sep 21, 2019
0.1.6 Sep 21, 2018

#1 in Rust patterns

Download history 174284/week @ 2020-05-30 189386/week @ 2020-06-06 179439/week @ 2020-06-13 186254/week @ 2020-06-20 183960/week @ 2020-06-27 192800/week @ 2020-07-04 163685/week @ 2020-07-11 166619/week @ 2020-07-18 192766/week @ 2020-07-25 202138/week @ 2020-08-01 194164/week @ 2020-08-08 210992/week @ 2020-08-15 218668/week @ 2020-08-22 206794/week @ 2020-08-29 204553/week @ 2020-09-05 206339/week @ 2020-09-12

774,514 downloads per month
Used in 2,037 crates (393 directly)

MIT/Apache

51KB
619 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

~150KB