sigp / superstruct

Rust library for versioned data types
https://sigp.github.io/superstruct/
Apache License 2.0
65 stars 3 forks source link

Feature request: Variant propagation in nested superstructs #30

Closed DragonDev1906 closed 8 months ago

DragonDev1906 commented 1 year ago

Let's say we have a nested struct, similar to nested example, but it has two inner variants that depend on the Variant. All using the same names for variants:

#[superstruct(variants(A, B), variant_attributes(derive(Debug, Clone)))]
#[derive(Debug, Clone)]
pub struct Outer {
    #[superstruct(only(A))]
    pub inner: InnerA,
    #[superstruct(only(B))]
    pub inner: InnerB,

    #[superstruct(only(A))]
    pub inner2: Inner2A,
    #[superstruct(only(B))]
    pub inner2: Inner2B,
}

This works but gets complicated quickly. I'd like to propose adding a same_variants attribute or something similar, which allows writing the above code as follows:

#[superstruct(variants(A, B), variant_attributes(derive(Debug, Clone)))]
#[derive(Debug, Clone)]
pub struct Outer {
    #[superstruct(same_variants]
    pub inner: Inner,

    #[superstruct(same_variants)]
    pub inner2: Inner2,
}

Combining this with only(...) would make writing such nested structs easier (and more readable), especially if there are a lot of different variants.

The alternative of using the Inner enum normally (i.e. the enum inside of Outer is sometimes not an option either, as the nested example already demonstrates.