Builder Macro
This crate contains a builder!
macro to declare a struct and a corresponding builder.
The macro is inspired from jadpole/builder-macro, and is designed to remove duplication of field declaration, as well as generating appropriate setter methods.
Include the macro inside your crate's lib.rs
or main.rs
.
extern crate builder_macro;
Examples
Non-consuming Builder
The simplest usage of the builder macro to generate a non-consuming builder is:
builder!;
The above will generate a module private struct and a non-consuming builder with a single private field.
For example, given the following declaration:
builder!;
The generated builder and struct will be:
The full macro usage format is:
// We declare the builder insider a module simply to demonstrate scope
let my_struct = new
.a_private_field
.build;
assert_eq!;
Consuming Builder
To generate a consuming builder, instead of using ->
, use =>
between the builder name and the target struct
name.
;
// Note: we use => instead of -> for the consuming variant of the builder
builder!;
let mut my_struct = new.build;
assert_eq!;
assert_eq!;
Visibility
Generate a builder and struct with module private visibility:
builder!;
let my_struct = new
.field_i32
.build;
assert_eq!;
assert_eq!; // uses default
Generate a builder and struct with public visibility:
let my_struct = new
.field_i32
.build;
assert_eq!;
// The next line will fail compilation if uncommented as field_str is private
// assert_eq!(my_struct.field_str, "abc");
License
The MIT License