Derive Macro simple_builder::Builder

source ·
#[derive(Builder)]
{
    // Attributes available to this derive:
    #[builder]
}
Expand description

Macro that derives a Builder object for any given struct. E.g. SomeType -> SomeTypeBuilder.

Simple-Builder takes ownership of inputs and stores them in an Option<T> for each field. Fields that are marked #[builder(required)] will be part of the new() call so they’re guaranteed to be set on the final object.

Example: Builder on a Simple Object


// Debug, PartialEq, Eq are only for assertions
#[derive(Debug, PartialEq, Eq, Builder)]
struct Breakfast {
    #[builder(required)]
    pub coffee: i64, // coffee is required, and therefore not Option<T>
    pub toast: Option<i64>,
    pub eggs: Option<i64>,
    pub bacon: Option<i64>,
}

pub fn main() {
    let desired_breakfast = Breakfast {
        coffee: 1,
        toast: None,
        eggs: Some(3),
        bacon: Some(2),
    };

    // semantically equivalent to `Breakfast::builder(16)`
    let mut builder = BreakfastBuilder::new(16);

    let breakfast = builder.eggs(3).bacon(2).build();

    assert_eq!(desired_breakfast, breakfast);
}

Attributes

Builder supports attributes under #[builder(...)] on individual fields to carry metadata. At this time, the available attributes are:

  • required – marks a field as required, meaning it can be T instead of Option<T> on the struct and will be an argument to the StructBuilder::new() or Struct::builder() methods.