I have an enum like this:
enum States {
A { opts: Vec<States> },
B { opts: Vec<States> },
C { opts: Vec<States> },
}
I'd like to implement the Default
trait for it. Not for the enum itself:
impl Default for States {
fn default() -> States {
States::A { vec![] }
}
}
but for States::A
, States::B
and States::C
, to have default values for opts
. Is it possible?
This is currently not possible because enum variants are not first class types. There is an open RFC that proposes "making enum variants first-class types": RFC 1450. Until that is accepted and implemented, the workaround most people use for this is to make proper structs for each variant, and then make a simple enum wrapping those structs:
struct A { opts: Vec<States> }
struct B { opts: Vec<States> }
struct C { opts: Vec<States> }
enum States {
A(A),
B(B),
C(C)
}
Then you can implement Default
for A
, B
, and C
.
impl Default for A {
fn default() -> A {
A { opts: Vec::new() }
}
}
and use them as A::default()
, B::default()
, and C::default()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With