Go to file
openharmony_ci ef40d7f6e6
!3 缺少bindgen/cxx/nix的被动依赖软件的开源声明
Merge pull request !3 from liangxinyan123/master
2024-02-20 02:21:55 +00:00
.github/workflows fix miri tests 2022-11-25 15:39:59 +00:00
design Add files via upload 2018-08-08 16:05:57 +03:00
examples fix lazy_static example bug 2022-08-22 16:20:14 +08:00
src Add once_cell::race::OnceRef 2022-12-28 23:58:56 -08:00
tests publish 1.16.0-pre.1 2022-10-22 19:25:26 +01:00
xtask fix miri tests 2022-11-25 15:39:59 +00:00
.gitignore ignore code 2020-08-17 23:01:48 +02:00
bors.toml Switch to xaction for CI 2020-11-11 01:38:33 +01:00
BUILD.gn Add GN Build Files and Custom Modifications 2023-04-12 17:26:35 +08:00
Cargo.lock.msrv MSRV is 1.56 2022-09-16 00:10:20 +01:00
Cargo.toml Add once_cell::race::OnceRef 2022-12-28 23:58:56 -08:00
CHANGELOG.md Add once_cell::race::OnceRef 2022-12-28 23:58:56 -08:00
LICENSE-APACHE Initial 2018-08-02 03:12:28 +03:00
LICENSE-MIT Initial 2018-08-02 03:12:28 +03:00
logo.svg Add files via upload 2018-08-08 16:05:57 +03:00
OAT.xml Add OAT.xml and README.OpenSource 2023-04-14 14:15:14 +08:00
README.md Add references to generic_once_cell 2022-11-10 15:02:43 +01:00
README.OpenSource IssueNo: https://gitee.com/openharmony/third_party_rust_bindgen/issues/I8ZMCP 2024-02-19 09:52:48 +08:00
rustfmt.toml reformat 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.