Can an enum containing some implementation implements automatically the trait

Let's say we have a trait and two implementations:

pub trait Trait1{}

pub struct Cls1{}
pub struct Cls2{}

impl Trait1 for Cls1{}
impl Trait1 for Cls2{}

Now we have an enum containing Cls1 and Cls2:

pub enum Enum1{
    A(Cls1),
    B(Cls2),
}

Is there any way to let Enum1 implements the Trait1 trait automatically since all its variants implement it.

No. Not completely implicitly.

However, there likely are crates that contain a macro for forwarding all methods of a given trait to all newtype variants.

Is there any way to let Enum1 implements the Trait1 trait automatically since all its variants implement it.

You will need to create your own custom derive macro and then you can derive the trait on your enum.

#[derive(Trait1)]
pub enum Enum1{
    A(Cls1),
    B(Cls2),
}
1 Like

thanks, I imagined this but I haven't got familiar with how to write custom derive macro, I can try it later

Thanks, I found enum_dispatch crate which can help me.

2 Likes

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.