25

If I have an enum with a set of values, is there a way I could create a second enum with the same variants plus some more?

// From this
enum Base {
    Alpha,
    Beta(usize),
}

// To this, but without copy & paste
enum Extended {
    Alpha,
    Beta(usize),
    Gamma,
}
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
  • A more complex form of this Question is [here](https://stackoverflow.com/questions/69218879/rust-extend-enum-result?noredirect=1#comment122342399_69218879). – JamesThomasMoon Sep 17 '21 at 09:15

1 Answers1

30

An enum can't be directly extended, but you use the same composition trick one would use with structs (that is, with a struct, one would have a field storing an instance of the 'parent').

enum Base {
    Alpha,
    Beta(usize),
}

enum Extended {
    Base(Base),
    Gamma
}

If you wish to handle each case individually, this is then used like

match some_extended {
    Base(Alpha) => ...,
    Base(Beta(x)) => ...,
    Gamma => ...
}

but you can also share/re-use code from the "parent"

match some_extended {
    Base(base) => base.do_something(),
    Gamma => ...,
}
JamesThomasMoon
  • 4,639
  • 6
  • 33
  • 42
huon
  • 83,735
  • 17
  • 214
  • 214
  • 9
    Interesting. But what if the "parental chain" gets longer, so the navigation `Base(Base(Base(Alpha)))` or `base.base.base.do_something()` gets endless? – iago-lito Feb 07 '18 at 12:57
  • 1
    I checked and was surprised to find that **the compiler will merge the discriminators**. So in this example `enum Parent{A,B}enum Child{Parent(Parent),C,D}`, the `Child` enum occupies one byte. – Indiana Kernick Dec 18 '20 at 06:07