# 概述
`once_cell` 提供了两种新的类似于单元的类型,分别是 `unsync::OnceCell` 和 `sync::OnceCell`。`OnceCell`
可以存储任意非`Copy`类型,最多只能被赋值一次,并提供直接访问
简要来说, API 的格式大致如下:
```rust
impl OnceCell {
fn new() -> OnceCell { ... }
fn set(&self, value: T) -> Result<(), T> { ... }
fn get(&self) -> Option<&T> { ... }
}
```
请注意,与 `RefCell` 和 `Mutex` 一样,`set` 方法只需要一个共享引用。
由于单次赋值限制, `get` 可以返回 `&T` 而不是 `Ref`
或 `MutexGuard`.
`once_cell` 还有一个 `Lazy` 类型,它基于 `OnceCell`,提供与 `OnceCell` 相同的 API。
`lazy_static!`宏,但不使用任何宏:
```rust
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());
}
更多模式和用例请参阅 [文档](https://docs.rs/once_cell/) !