#智能指针 #容器 #向下转型 #线程安全 #读写锁 #存储 #引用计数

any_handle

一个线程安全、类型安全的智能指针,可以共享、存储和向下转型 dyn Any

5个版本

0.1.4 2023年5月11日
0.1.3 2023年5月11日
0.1.2 2023年5月11日
0.1.1 2023年5月11日
0.1.0 2023年5月11日

#1720数据结构

36 每月下载
2 crates 中使用

MIT 协议

9KB
92

any_handle

Crates.io docs.rs GitHub Workflow Status Crates.io

any_handle 提供了一个引用计数智能指针类型 AnyHandle<T>,它可以存储类型 T 的值。特殊的 AnyHandle<dyn Any> 允许向下转型为任何其他 AnyHandle<T: Any> 类型。

内部,AnyHandle 是一个 Arc<RwLock<Box<dyn Any>>>,并且与 Arc 的引用计数行为以及 RwLock 的多读者或单写者线程安全模型相匹配。

use any_handle::{AnyHandle, Any};
struct SomeStruct (i32);

fn main() -> Option<()>{
    // Initialize a handle with an unknown type.
    // If you want to pass in a Box<dyn SomeOtherTrait>, instead of a concrete
    // type, you will have to use `#![feature(trait_upcasting)]`, unfortunately.
    let handle: AnyHandle<dyn Any> = AnyHandle::new(Box::new(SomeStruct(12)));
    // Now we can put it in some sort of generic container...
    
    // ...and when we retrieve it later:
    let mut handle: AnyHandle<SomeStruct> = handle.downcast().ok()?;
    handle.write().do_mut_things_with();
    handle.read().do_things_with();
    Some(())
}

无运行时依赖