Let's say I want to store elements of different types in HashMap
but all of them will implement some trait. And I want to be able to retrieve element casted to the right type. The choice of the key allows me to be sure about the type of the element (in the example below type id of the object is a part of the key). How to properly convert found element to T
?
use std::collections::HashMap;
use std::any::TypeId;
use std::rc::Rc;
trait MyTrait {
fn new() -> Self where Self: Sized;
// Other methods
}
struct MyStruct {
items: HashMap<(i32, TypeId), Rc<dyn MyTrait>>
}
impl MyStruct {
fn get<T: MyTrait + 'static>(&mut self, key: i32) -> Rc<T> {
if let Some(item) = self.items.get(&(key, TypeId::of::<T>())) {
item.clone() as Rc<T> // !!! Compilation error !!!
} else {
let item = Rc::new(T::new());
self.items.insert((key, TypeId::of::<T>()), item.clone());
item
}
}
}