5

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.

12
  • If you are willing to go unsafe, you could save them as std::raw::TraitObject values or an equivalent non-nightly type. Highly unsafe and tricky to do right, but possible.
    – rodrigo
    Commented Aug 15, 2020 at 15:20
  • I actually think this is an oversight in the standard library. Maybe it's worth opening an issue? I think that Any::is, as well as all of the downcast_* methods in the standard library, should probably accept unsized types.
    – Coder-256
    Commented Aug 16, 2020 at 4:59
  • 1
    @rodrigo std::raw::TraitObject does not have the same layout as an Rc<dyn Trait>, since it also has a pointer to the ref counts.
    – Peter Hall
    Commented Aug 16, 2020 at 5:06
  • @Coder-256 It's not an oversight, it's a logical consequence of the lack of RTTI in Rust. 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.
    – trent
    Commented Aug 17, 2020 at 13:43
  • 1
    Does this answer your question? How can I downcast from Box<Any> to a trait object type? Relevant excerpt: "you can only have one level of traityness[...] if you take a type Widget that implements WidgetTrait and box it in a Box<Any>, you can only get it out as a Widget object, not as a Box<WidgetTrait> object."
    – trent
    Commented Aug 17, 2020 at 15:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.