Search code examples
enumsrustdefault

Use Default trait for struct as enum option


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?


Solution

  • 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().