2024-02-19 09:52:48 +08:00
2022-11-25 15:39:59 +00:00
2018-08-08 16:05:57 +03:00
2022-08-22 16:20:14 +08:00
2022-12-28 23:58:56 -08:00
2022-10-22 19:25:26 +01:00
2022-11-25 15:39:59 +00:00
2020-08-17 23:01:48 +02:00
2020-11-11 01:38:33 +01:00
2022-09-16 00:10:20 +01:00
2022-12-28 23:58:56 -08:00
2022-12-28 23:58:56 -08:00
2018-08-02 03:12:28 +03:00
2018-08-02 03:12:28 +03:00
2018-08-08 16:05:57 +03:00
2023-04-14 14:15:14 +08:00
2022-11-10 15:02:43 +01:00
2019-09-01 14:25:59 +03:00

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.

S
Description
提供一种在不使用互斥锁的情况下实现只初始化一次的单元格类型。 | A Rust library that provides a cell that can only be written to once.
Readme 1.7 MiB
Languages
Rust 100%