Can enum enforce all types to implement a trait and then cast to &dyn Trait?


Can enums in rust enforce all options' types to implement a trait Trait, and then cast this enum to &dyn Trait?

I think it should be possible to store the virtual table for a trait for each of the types inside the enum, and then safely cast it to &dyn Trait.

It would allow dynamic dispatch of multiple types, while not requiring heap, only space for the largest type in the enum.

This is not built into the language, but it's as easy as

impl Trait for MyEnum {
    fn my_method(&self) -> RetTy {
        match *self {
            MyEnum::Foo(ref foo) => foo.my_method(),
            MyEnum::Bar(ref bar) => bar.my_method(),
            MyEnum::Qux(ref qux) => qux.my_method(),

and once MyEnum implements Trait, then you can just coerce &MyEnum to &dyn Trait. No heap allocation needed.

You might also be interested in enum_dispatch.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.