Here is a simplified example of my problem:

struct User;
struct Community;

enum Actor {
    User(User),
    Community(Community),
}

trait Name {
    fn name() -> &'static str;
}

impl Name for User {
    fn name() -> &'static str { "/u/nutomic" }
}

impl Name for Community {
    fn name() -> &'static str { "/c/rust " }
}

fn main() {
    let actor = Actor::Community(Community);
    println!("{}", actor.name());
}

Playground link

As you may have noticed, this doesnt compile. The only solution I can think of is with a match. I want to avoid that because I have an enum with 30+ variants, and a trait with multiple methods. So that would be a huge match statement in each method, when the compiler should know that the enum variants all have the same trait.

So, do you know any way to make this work without match?

  • pingveno
    link
    fedilink
    arrow-up
    2
    ·
    3 years ago

    I remember seeing a crate somewhere where it implements a trait if all of the variants are tuple struct variants (wrong name) that implement that trait. Not sure what it’s called.

    • nutomicOPMA
      link
      fedilink
      arrow-up
      1
      ·
      3 years ago

      Maybe this one? Unfortunately it doesnt work in my case, because I have a bunch of derived traits, generics and async. Maybe a new derive trait could be written to solve this problem.