Build Status Coverage Status Latest Version Documentation

Builder Pattern Derive

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.

This requires Rust 1.15, due to the usage of Macros 1.1.

How it Works

```rust

[macro_use]

extern crate derive_builder;

[derive(Default, Builder, Debug)]

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

[derive(Clone, Default)]

struct ChannelBuilder { token: Option, special_info: Option, }

[allow(dead_code)]

impl ChannelBuilder { pub fn token>(&mut self, value: VALUE) -> &mut Self { let mut new = self; new.token = Some(value.into()); new } pub fn specialinfo>(&mut self, value: VALUE) -> &mut Self { let mut new = self; new.specialinfo = Some(value.into()); new } fn build(&self) -> Result { Ok(Channel { token: Clone::clone(self.token .asref() .okor( "token must be initialized")?), specialinfo: Clone::clone(self.specialinfo .asref() .okor("special_info must be initialized")?), }) } } ```

Get Started

It's as simple as two steps:

  1. Add derive_builder to your Cargo.toml either manually or with cargo-edit:

  2. Annotate your struct with #[derive(Builder)]

Usage and Features

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. :-)

Gotchas

Documentation

Detailed explaination of all features and tips for troubleshooting. You'll also find a discussion of different builder patterns.

Changelog

Yes, we keep a changelog.

License

Licensed under either of

at your option.

Contribution

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.