How to cast one dyn trait to another dyn trait

Hello, I have a certain group of structs that all implement lets say TraitA. My issue is that some of them (not all) also implement TraitB. So I want to be able to convert TraitA, to TraitB, one way of doing this is creating a method for TraitA, as_trait_b which will return Option<&dyn TraitB>. And while I'm considering this the issue is that there is also TraitC, TraitD, and possibly more traits that will have to be added in the future that might be implemented for structs with TraitA. So I was wondering if there is any way of preforming this conversion without having to handle adding more functions to TraitA.

There's no way in rust to do that unfortunately. The best I can think of is using the bevy_reflect crate, though you have to use a few macros.

However, trait upcasting will soon be stabilized in rust. So maybe in the future, rust would have a way to cast between two unrelated traits

3 Likes

If it's "not always", then you're probably never going to get a better solution than the function on the trait returning an option, like you describe.

4 Likes

Note that trait upcasting requires one trait to be a supertrait of the other, so they still need to be strongly related.

2 Likes

Its hard to say without knowing what you're actually trying to do, and I know this is not the answer to your question, but why do you need to convert one trait to another in the first place ? You might be looking at the problem from the wrong perspective.

1 Like

In my specific issue the structs represent services, and Traits represent common functionality shared by some of those services. I spawn multiple instances of those services, store them in an array with Box<dyn CommonTrait>. My problem is that sometimes I want to iter though this array and if a certain services implement a certain feature I want to run a function that executes a code related to that feature.

Heavily over simplified but that should be a gist of it.