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.
std::raw::TraitObject
values or an equivalent non-nightly type. Highly unsafe and tricky to do right, but possible.Any::is
, as well as all of thedowncast_*
methods in the standard library, should probably accept unsized types.std::raw::TraitObject
does not have the same layout as anRc<dyn Trait>
, since it also has a pointer to the ref counts.dyn Any
doesn't retain enough information about the concrete type to "know" whether it implements any arbitrary trait, so such a method would have to materialize a vtable-pointer out of thin air.Widget
that implementsWidgetTrait
and box it in aBox<Any>
, you can only get it out as aWidget
object, not as aBox<WidgetTrait>
object."