colin-kiegel / rust-derive-builder

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

Feature Request: flatten for substructs #255

Closed EvanCarroll closed 2 years ago

EvanCarroll commented 2 years ago

It would be nice to be able to flatten structs that also implement builder.

#[derive(builder)]
struct Foo {
  bar: u32
}

#[derive(builder)]
struct Baz {
  #[builder(flatten)]
  foo: Foo // which itself derives Builder
}

// .bar() here comes from flattening `foo`
let baz = BazBuilder::from().bar(42).build().unwrap();
TedDriggs commented 2 years ago

I don't think this is possible: It would require the parent to know the methods of the child, and Rust macros don't have a way to access that data.

serde is able to support flattening because it doesn't generate methods per-field, so it can wait until runtime and then pass values down to the flattened Deserializer instances. It's very elegant, but it also doesn't work for our use-case.

@ijackson explored nested builders in #254, but that wasn't quite flattening.