#builder #struct #object #macro #procedural #proc-macro #required

macro simple-builder-macro

A procedural macro for creating a Builder object for any struct

1 unstable release

0.0.2 Oct 12, 2023

#109 in #required

Download history 15/week @ 2024-08-31 3/week @ 2024-09-07 2/week @ 2024-09-14 20/week @ 2024-09-21 31/week @ 2024-09-28 30/week @ 2024-10-05 31/week @ 2024-10-12 8/week @ 2024-10-19 5/week @ 2024-11-09 24/week @ 2024-11-16 7/week @ 2024-11-23 9/week @ 2024-11-30 37/week @ 2024-12-07 15/week @ 2024-12-14

73 downloads per month
Used in 2 crates (via simple-builder)

MIT license

11KB
198 lines

simple-builder

A simple implementation of the builder pattern for arbitrary Rust structs.

badge License: MIT

This package could easily be called "yet-another-builder" (YAB for short), but it fills a niche for those looking less for features in a builder implementation, and more for ease of use. In particular this implementation is for you if you have structs with several required fields and many optional ones. Examples of this might be query parameters for endpoints with required fields like a nonce and id, then many optional filtering parameters like start and end dates, price ranges, product types, etc. This macro was purpose built for this very use case.

Example: Simple Use Case

use simple_builder_macro::Builder;

// 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);
}

lib.rs:

A procedural macro for creating a Builder object for any struct. This crate is meant to be used by the simple-builder crate and is not meant for direct consumption.

Dependencies

~215–650KB
~16K SLoC