Skip to content

Support flattened builders #274

@cbgbt

Description

@cbgbt

Hello,

bon is great, thanks for sharing it!

I have a use-case where I have a large variety of structs that are all subtly different. I'm wondering if it would be possible to include a macro similar to serde(flatten) that would allow common attributes to be lifted into a different Builder struct, but hide that fact from users of the builder API.

As an example:

#[derive(Builder)]
#[builder(on(String, into))]
struct Common {
    commonA: String,
    commonB: String,
}


#[derive(Builder)]
#[builder(on(String, into))]
struct Child {
    #[builder(flatten)]
    common: Common,
    customFieldA: String,
}

Which would allow you to do something like:

let child = Child::builder()
    .commonA("sets commonA for `Common`'s builder")
    .commonB("sets commonB for `Common`'s builder")
    .customFieldA("sets customFieldA for `Child`'s builder")
    .build() // finalizes both builders

I haven't toyed with this much yet, but it seems like custom fields and methods could enable this currently.

A note for the community from the maintainers

Please vote on this issue by adding a 👍 reaction to help the maintainers with prioritizing it. You may add a comment describing your real use case related to this issue for us to better understand the problem domain.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions