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.
```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(private)]
.Into
trait for the field type.VALUE
, because this is already reserved for the setter-methods.RUST_LOG=derive_builder=trace
.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.