colin-kiegel / rust-derive-builder

derive builder implementation for rust structs
https://colin-kiegel.github.io/rust-derive-builder/
Apache License 2.0
1.28k stars 82 forks source link

Support for builders on enums #268

Closed sazzer closed 1 year ago

sazzer commented 1 year ago

As best I can see, all of the builders here work only on structs. There are cases where it could be useful to support them on enums as well, with different builders for each enum branch.

This would allow for a single type that can have different shapes, and where each of those shapes can be built using the builder patter.

For example, I'm currently building a HAL-FORMS implementation. Part of this is the Option concept, which is either Inline or Link, but should never be both or neither. This fits really well as an enum, but then I can't use derive_builder with it, which is a shame.

TedDriggs commented 1 year ago

This would allow for a single type that can have different shapes, and where each of those shapes can be built using the builder patter.

This is achievable today. I'd suggest following the example of syn for this.

#[derive(Builder)]
pub struct OptionInline {}

#[derive(Builder)]
pub struct OptionLink {}

pub enum Option {
    Inline(OptionInline),
    Link(OptionLink),
}

I have another crate called from_variants which generates From conversions on Option so you can call into() on an OptionInline and get an Option back.

The per-variant structs also make it possible to enforce at compile-time that some functions only operate on inline (or link) options.