Is there a way to avoid writing duplicated on trait enums?

Hi, here's a sample code about enums and the trait:

trait T {
  pub fn hello() {}
}

struct A {}
impl T for A {}
impl A {
  fn ok() {}
}

struct B {}
impl T for B {}
impl B {
  fn bye() {}
}

enum E {
  A(A),
  B(B),
}

// This part of code is duplicated, and should be avoid {

impl T for E {
  fn hello() {
    match self {
      E::A(a) => a.hello(),
      E::B(b) => b.hello(),
    }
  }
}

// This part of code is duplicated, and should be avoid }

fn main() {
  let objs : Vec<E> = vec![E::A(A{}), E::B(B{})];
  for o in objs {
    o.hello();
    match o {
      E::A(a) => a.ok(),
      E::B(b) => b.bye(),
    }
  }
}

I want to eliminate the impl T for E part of code, because it only forwards all APIs to its variants.

The enum_dispatch crate will generate this code for you.

3 Likes

The enum_dispatch crate works great, until I try to use it for 1 single enum with 2 traits. Here is a sample code which shows the basic idea:


use enum_dispatch::enum_dispatch;

#[enum_dispatch]
trait T1 { fn hello1(&self) {} }

#[enum_dispatch]
trait T2 { fn hello2(&self, message: &str) {} }

struct A {}
impl T1 for A { fn hello1(&self) {} }
impl T2 for A { fn hello2(&self, message: &str) {} }

struct B {}
impl T1 for B { fn hello1(&self) {} }
impl T2 for B { fn hello2(&self, message: &str) {} }

#[enum_dispatch(T1)]
#[enum_dispatch(T2)]
enum E {
 A(A),
 B(B),
}

The compilation will fail on this case. I have no idea how to fix it....

I think the syntax for multiple traits is:

#[enum_dispatch(T1, T2)]
2 Likes

Yes, I confirmed this.

2 Likes

Then it should be my issue, I will check again my real-world use case.

Thank you a lot, really.

1 Like