Cast Rc<Any> to Rc<Trait>

Viewed 316

I'm trying to create a map, where a key is a TypeId of a trait and a value is a struct that implements it.

impls: HashMap<TypeId, Rc<dyn Any>>

To put a new object to the map, I use the next code:

let type_id = TypeId::of::<dyn Trait>();
let obj_ref: Rc<dyn Any> = Rc::new(obj);

self.impls.insert(type_id, Rc::clone(&obj_ref));

But when I try to get this object from the map, I need to cast it back.

let any_comp_ref = self.impls
    .get(&TypeId::of::<dyn Trait>())
    .expect(&format!("Object for type: {} is not found", type_name::<dyn Trait>()));

let result: &dyn Trait = // ???

I've tried to use Rc::downcast. But it's implemented only for Sized types.

0 Answers
Related