4个版本
| 0.1.3 | 2023年1月27日 | 
|---|---|
| 0.1.2 | 2023年1月25日 | 
| 0.1.1 | 2023年1月25日 | 
| 0.1.0 | 2023年1月24日 | 
#82 in #initialization
每月下载量30次
用于 mtcp-rs
27KB
346 行代码(不包括注释)
lazy_rc – 懒Rc和Arc 
lazy_rc提供了Rc<T>和Arc<T>的懒初始化实现。
Crates.io
https://crates.io/crates/lazy_rc
lib.rs:
lazy_rc提供了Rc<T>和Arc<T>的懒初始化实现。
换句话说,当第一次访问时,LazyRc
线程安全
LazyRc<T>是单线程的,因为RcLazyRc<T>用于static变量。然而,它可以用于thread_local!变量。
LazyArc<T> 是 线程安全的,因为 Arc<T> 也是线程安全的。因此,LazyArc<T> 实例可以被多个线程共享,甚至可以使用 LazyArc<T> 作为 全局 静态 变量。
常量警告
请不要将 LazyRc<T> 或 LazyArc<T> 作为 常量 值使用!这是因为,在 Rust 中,常量 值是“内联”的,实际上在每个使用 常量 值的地方创建了一个 新的 实例。这显然打破了“延迟”初始化 😨
示例
use lazy_rc::{LazyRc, LazyArc};
static GLOBAL_INSTANCE: LazyArc<MyStruct> = LazyArc::empty();
thread_local! {
    static THREAD_INSTANCE: LazyRc<MyStruct>  = LazyRc::empty();
}
struct MyStruct {
   /* ... */
}
impl MyStruct {
    fn new() -> Result<Self> {
        /* ... */
    }
    /// Returns a thread-local instance that will be created on first access.
    /// If the initialization function fails, then an Error will be returned.
    pub fn instance() -> Result<Rc<Self>> {
        THREAD_INSTANCE.with(|lazy| lazy.or_try_init_with(Self::new))
    }
}