use std::any::Any;
use std::collections::HashMap;
struct Container {
items: HashMap<String, Box<dyn Any>>,
}
impl Container {
fn new() -> Self {
Self {
items: HashMap::new(),
}
}
fn insert<T: 'static>(&mut self, key: &str, value: T) {
self.items.insert(key.to_string(), Box::new(value));
}
fn get<T: 'static>(&self, key: &str) -> Option<&T> {
self.items.get(key)?.downcast_ref::<T>()
}
}
struct MyStruct {
value: i32,
}
impl MyStruct {
fn new() -> Self {
Self { value: 42 }
}
}
#[test]
fn test001() {
let mut container = Container::new();
container.insert("new_fn", MyStruct::new as fn() -> MyStruct);
container.insert("new_closure", Box::new(|| MyStruct { value: 100 }) as Box<dyn Fn() -> MyStruct>);
if let Some(f) = container.get::<fn() -> MyStruct>("new_fn") {
let obj = f();
println!("from fn pointer: {}", obj.value); }
if let Some(f) = container.get::<Box<dyn Fn() -> MyStruct>>("new_closure") {
let obj = f();
println!("from closure: {}", obj.value); }
}