27 releases (10 stable)

1.5.2 Nov 12, 2020
1.4.1 Aug 17, 2020
1.4.0 May 13, 2020
1.3.1 Jan 17, 2020
0.1.6 Sep 21, 2018

#1 in Rust patterns

Download history 194690/week @ 2020-08-09 213363/week @ 2020-08-16 218747/week @ 2020-08-23 203882/week @ 2020-08-30 206317/week @ 2020-09-06 220966/week @ 2020-09-13 221829/week @ 2020-09-20 233820/week @ 2020-09-27 239016/week @ 2020-10-04 245509/week @ 2020-10-11 251839/week @ 2020-10-18 257313/week @ 2020-10-25 250231/week @ 2020-11-01 268058/week @ 2020-11-08 292392/week @ 2020-11-15 250225/week @ 2020-11-22

984,932 downloads per month
Used in 3,591 crates (486 directly)

MIT/Apache

61KB
780 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