#derive #macro #builder #setter #struct

macro derive_builder

Rust macro to automatically implement the builder pattern for arbitrary structs

21 releases

0.9.0 Nov 7, 2019
0.7.2 Jun 8, 2019
0.7.1 Feb 5, 2019
0.7.0 Oct 22, 2018
0.2.1 Sep 24, 2016

#5 in Rust patterns

Download history 7516/week @ 2019-12-17 5270/week @ 2019-12-24 6471/week @ 2019-12-31 10294/week @ 2020-01-07 12496/week @ 2020-01-14 13598/week @ 2020-01-21 17936/week @ 2020-01-28 13654/week @ 2020-02-04 13554/week @ 2020-02-11 14814/week @ 2020-02-18 17358/week @ 2020-02-25 15232/week @ 2020-03-03 14120/week @ 2020-03-10 13748/week @ 2020-03-17 14327/week @ 2020-03-24 15783/week @ 2020-03-31

31,589 downloads per month
Used in 189 crates (97 directly)



Build status Rust version Documentation Latest version All downloads Downloads of latest version

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.

How it Works

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

#[derive(Clone, Default)]
struct ChannelBuilder {
    token: Option<i32>,
    special_info: Option<i32>,

impl ChannelBuilder {
    pub fn token<VALUE: Into<i32>>(&mut self, value: VALUE) -> &mut Self {
        let mut new = self;
        new.token = Some(value.into());
    pub fn special_info<VALUE: Into<i32>>(&mut self, value: VALUE) -> &mut Self {
        let mut new = self;
        new.special_info = Some(value.into());
    fn build(&self) -> Result<Channel, String> {
        Ok(Channel {
            token: Clone::clone(self.token
                       "token must be initialized")?),
            special_info: Clone::clone(self.special_info
                .ok_or("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:
  • cargo add derive_builder
  1. Annotate your struct with #[derive(Builder)]

Usage and Features

  • Chaining: The setter calls can be chained, because they consume and return &mut self by default.
  • Builder patterns: You can opt into other builder patterns by preceding your struct (or field) with #[builder(pattern = "owned")] or #[builder(pattern = "immutable")].
  • Extensible: You can still define your own implementations for the builder struct and define additional methods. Just make sure to name them differently than the setter and build methods.
  • Documentation and attributes: Setter methods can be documented by simply documenting the corresponding field. Similarly #[cfg(...)] and #[allow(...)] attributes are also applied to the setter methods.
  • Hidden fields: You can skip setters via #[builder(setter(skip))] on each field individually.
  • Setter visibility: You can opt into private setter by preceding your struct with #[builder(private)].
  • Setter type conversions: With #[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.
  • Setter strip option: With #[builder(setter(strip_option))], setter methods will take T as parameter'type for field of type Option<T>.
  • Builder field visibility: You can use #[builder(field(private))] or ..(public), to set field visibility of your builder.
  • Generic structs: Are also supported, but you must not use a type parameter named VALUE, if you also activate setter type conversions.
  • Default values: You can use #[builder(default)] to delegate to the Default implementation or any explicit value via = "..". This works both on the struct and field level.
  • Pre-build validation: You can use #[builder(build_fn(validate = "path::to::fn"))] to add your own validation before the target struct is generated.
  • Build method suppression: You can use #[builder(build_fn(skip))] to disable auto-implementation of the build method and provide your own.
  • Builder derivations: You can use #[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.
  • no_std support: Just add #[builder(no_std)] to your struct and add #![feature(alloc)] extern crate alloc to your crate. The latter requires the nightly toolchain.
  • Logging: If anything works unexpectedly you can enable detailed logs in two steps. First, add features = ["logging"] to the derive_builder dependency in Cargo.toml. Second, set this environment variable before calling cargo 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. :-)


  • Tuple structs and unit structs are not supported as they have no field names. We do not intend to support them.
  • When defining a generic struct, you cannot use 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.


~42K SLoC