use std::{any::{Any, TypeId}, collections::HashMap};
use once_cell::sync::Lazy;
use std::sync::Mutex;
static IOC: Lazy<Mutex<HashMap<TypeId, Box<(dyn Any + Send)>>>> = Lazy::new(|| {
let map = HashMap::new();
Mutex::new(map)
});
#[derive(Debug)]
struct Foo {
cat: String,
mouse: i32,
}
#[derive(Debug)]
struct Bar {
pro1: String,
pro2: i32,
pro3: f64
}
fn main() {
IOC.lock().unwrap().insert(TypeId::of::<Foo>(), Box::new(Foo{cat: "aa".to_string(), mouse: 33}));
IOC.lock().unwrap().insert(TypeId::of::<Bar>(), Box::new(Bar{pro1: "bb".to_string(), pro2: 66, pro3: 99.4}));
let ioc_tmp = IOC.lock().unwrap();
let foo = ioc_tmp.get(&TypeId::of::<Foo>()).unwrap();
let casted_foo = foo.downcast_ref::<Foo>();
let bar = ioc_tmp.get(&TypeId::of::<Bar>()).unwrap();
let casted_bar = bar.downcast_ref::<Bar>();
println!("{:?}--{:?}", casted_foo, casted_bar);
}
标签:容器,TypeId,unwrap,casted,let,new,IOC,Rust From: https://www.cnblogs.com/silentdoer/p/16772440.html