I want to implement a class Storage
that can store objects of any types. I am trying to do that using trait Any
. The Storage::insert::<T>(key, value)
should add a pair, where the key is always some String
type, and the value can be any type. When I store a Box<HashMap<String, dyn Any>>
the compiler says that it doesn't have size at compile-time. So how can I avoid that error ?
use std::any::{Any, TypeId};
use std::collections::hash_map::Keys;
use std::collections::HashMap;
pub struct Storage where Self: Sized{
map: Box<HashMap<String, dyn Any>>,
}
impl Storage {
pub fn new() -> Self {
Self {
map: Some(Box::new(HashMap::new())),
}
}
pub fn insert<Q: Any>(&mut self, key: &dyn Any, obj: Q) {
if key.is::<String>() {
let key_string = key.downcast_ref::<String>().unwrap();
self.map.as_mut().insert(key_string.clone(), obj);
}
}
}
Also I'm not sure that such class can be implemented with std::collections::HashMap