Buildstructor: a proc macro to build builders from constructors

68 points Mundane_Worldliness1

This is my first crate!

buildstructor is a proc macro that creates builders for your constructors.

buildstructor = "0.1.12"

The difference between this and other builder macro crates is that constructors are used to derive builders rather than structs. This results in a more natural fit with regular Rust code, and no annotation magic to define behavior.

pub struct MyStruct {
    sum: usize,
}

#[buildstructor::builder]
impl MyStruct {
    fn new(a: usize, b: usize) -> MyStruct {
        Self { sum: a + b }
    }
}

fn main() {
    let mine = MyStruct::builder().a(2).b(3).build();
    assert_eq!(mine.sum, 5);
}

Nice things:

  • You can specify fields in your constructor that do not appear in your struct.
  • No magic to default values, just use an Option param in your constructor and default as normal.
  • async constructors derives async builders.
  • Fallible constructors (Result) derives fallible builders.
  • Special Vec, Deque, Heap, Set, Map support. Add single or multiple items.
  • Multiple constructors = multiple builders.