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

⚓ Rust    📅 2025-06-30    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

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.

2 posts - 2 participants

Read full topic

🏷️ rust_feed