Add builder method to struct in builder pattern (#251)

pull/109/merge
bemyak 3 years ago committed by GitHub
parent fb57f21ec1
commit a22d81d751
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -13,6 +13,14 @@ pub struct Foo {
bar: String,
}
impl Foo {
// This method will help users to discover the builder
pub fn builder() -> FooBuilder {
FooBuilder::default()
}
}
#[derive(Default)]
pub struct FooBuilder {
// Probably lots of optional fields.
bar: String,
@ -103,6 +111,6 @@ as well as the `FooBuilder::new().a().b().build()` style.
- [Description in the style guide](https://web.archive.org/web/20210104103100/https://doc.rust-lang.org/1.12.0/style/ownership/builders.html)
- [derive_builder](https://crates.io/crates/derive_builder), a crate for automatically
implementing this pattern while avoiding the boilerplate.
- [Constructor pattern](../idioms/ctor.md) for when construction is simpler.
- [Constructor pattern](../../idioms/ctor.md) for when construction is simpler.
- [Builder pattern (wikipedia)](https://en.wikipedia.org/wiki/Builder_pattern)
- [Construction of complex values](https://web.archive.org/web/20210104103000/https://rust-lang.github.io/api-guidelines/type-safety.html#c-builder)

Loading…
Cancel
Save