Impl trait for enum variant


#1

Perhaps this is a terrible idea, has already been discussed, or is already possible in ways I don’t know, but what if it were possible to implement a trait for all variants of an enum? Something like this:

enum Thing {
  A,
  B
}

trait Foo {
  fn bar() -> usize;
}

impl Foo for Thing::A {
  fn bar() -> usize {
    1
  }
}

impl Foo for Thing::B {
  fn bar() -> usize {
    2
  }
}

Which would act as sugar for:

impl Thing {
  pub fn bar(self) -> usize {
    match self {
      Thing::A => 1,
      Thing::B => 2
    }
  }
}

#2

I don’t really understand how this is different from impl Foo for Thing. If you’re going to be required to impl Foo for every variant of Thing, why not just impl it on Thing directly? What does this proposal allow you to do that wouldn’t otherwise be possible?


#3

It seems like a convenient way to split the match arms up, which would be nice if the variant-specific functionality were non-trivial.


#4

This is related to RFC 1450, which makes Thing::A a type. This would be the next step I guess.

I think there should still be something to mark the trait as implemented on the enum. #[derive(Foo)] for example


#5

Thanks! That appears to be what I’m looking for.