chensk
1
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.
H2CO3
2
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
chensk
4
thanks, I imagined this but I haven't got familiar with how to write custom derive macro, I can try it later
chensk
5
Thanks, I found enum_dispatch crate which can help me.
2 Likes
system
Closed
6
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.