Rust macro to automatically implement the builder pattern for arbitrary structs. A simple #[derive(Builder)] will generate a FooBuilder for your struct Foo with all setter-methods and a build method.
```rust
extern crate derive_builder;
struct Channel { token: i32, special_info: i32, // .. a whole bunch of other fields .. }
fn main() { // builder pattern, go, go, go!... let ch = ChannelBuilder::default() .special_info(42u8) .token(19124) .build() .unwrap(); println!("{:?}", ch); } ```
Note that we did not write any definition or implementation of ChannelBuilder. Instead the derive_builder crate acts on #[derive(Builder)] and generates the necessary code at compile time.
This is the generated boilerplate code you didn't need to write. :-)
```rust,ignore
struct ChannelBuilder {
token: Option
impl ChannelBuilder {
pub fn token
It's as simple as two steps:
Add derive_builder to your Cargo.toml either manually or
with cargo-edit:
cargo add derive_builder#[derive(Builder)]&mut self by default.#[builder(pattern = "owned")] or #[builder(pattern = "immutable")].#[cfg(...)] and #[allow(...)] attributes are also applied to the setter methods.#[builder(setter(skip))] on each field individually.#[builder(private)].#[builder(setter(into))], setter methods will be generic over the input types – you can then supply every argument that implements the Into trait for the field type.#[builder(setter(strip_option))], setter methods will take T as parameter'type for field of type Option<T>.#[builder(field(private))] or ..(public), to set field visibility of your builder.VALUE, if you also activate setter type conversions.#[builder(default)] to delegate to the Default implementation or any explicit value via = "..". This works both on the struct and field level.#[builder(build_fn(validate = "path::to::fn"))] to add your own validation before the target struct is generated.#[builder(build_fn(skip))] to disable auto-implementation of the build method and provide your own.#[builder(derive(Trait1, Trait2, ...))] to have the builder derive additonal traits. All builders derive Default and Clone, so you should not declare those in this attribute.#[builder(no_std)] to your struct and add #![feature(alloc)] extern crate alloc to your crate. The latter requires the _nightly toolchain.For more information and examples please take a look at our documentation.
This is a work in progress. So expect even more features in the future. :-)
VALUE as a generic parameter as this is what all setters are using.Detailed explaination of all features and tips for troubleshooting. You'll also find a discussion of different builder patterns.
Yes, we keep a changelog.
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.