rust-typed-builder icon indicating copy to clipboard operation
rust-typed-builder copied to clipboard

Add flatten feature

Open poelzi opened this issue 1 year ago • 2 comments

It would be nice there is a builder(flatten) to merge 2 structs into one builder.

#[derive(TypedBuilder)]
struct A {
  a: String,
}
#[derive(TypedBuilder)]
struct A {
  #[builder(flatten)]
  shared: A,
  more: bool,
}

let a1 = A::builder().a("test".into()).more(true).build();

This should create a builder that will construct and fill the shared structure. Similar to serde(flatten). This is a common used data structure and would simplify usage.

poelzi avatar Mar 21 '23 06:03 poelzi

Sadly, I don't think this is possible with Rust's macro system. The derive macro on the outer type has no access to the structure of the inner types, and thus cannot generate withers for their fields.

idanarye avatar Mar 21 '23 11:03 idanarye

You would need to provide the fields of the struct to flatten, in this example: #[builder(flatten({a: String}))]. This could be automated with a macro that wraps both types, but it will get complicated and ugly...

mo8it avatar Jun 04 '23 12:06 mo8it