#lazy #static

once_cell

Single assignment cells and lazy values

31 releases (14 stable)

new 1.7.2 Mar 2, 2021
1.5.2 Nov 12, 2020
1.4.0 May 13, 2020
1.3.1 Jan 17, 2020
0.1.6 Sep 21, 2018

#9 in Rust patterns

Download history 292392/week @ 2020-11-15 259294/week @ 2020-11-22 277813/week @ 2020-11-29 268317/week @ 2020-12-06 258123/week @ 2020-12-13 193596/week @ 2020-12-20 185085/week @ 2020-12-27 278013/week @ 2021-01-03 302337/week @ 2021-01-10 288423/week @ 2021-01-17 373782/week @ 2021-01-24 380988/week @ 2021-01-31 384050/week @ 2021-02-07 396716/week @ 2021-02-14 455956/week @ 2021-02-21 447495/week @ 2021-02-28

1,346,520 downloads per month
Used in 5,201 crates (681 directly)

MIT/Apache

64KB
856 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

~135KB