Opinionated and Option-based builder pattern macro for Rust
Motivation
A derive macros to support a builder pattern for Rust:
- Everything except
Option<>
fields and explicitly defineddefault
attribute in structs are required, so you don't need any additional attributes to indicate it, and the presence of required params is checked at the compile time (not at the runtime). - To create new struct instances there is
::new
and an auxiliary init struct definition with only required fields (to compensate the Rust's named params inability).
Usage
Add this to your Cargo.toml
:
[]
= "0.4"
The macros generates the following functions and instances for your structures:
with/without/opt_<field_name>
: immutable setters for fields (opt
is an additional setter forOption<>
input argument)<field_name>/reset/mopt_<field_name>
: mutable setters for fields (mopt
is an additional setter forOption<>
input argument)new
: factory method with required fields as argumentsFrom<>
instance from an an auxiliary init struct definition with only required fields. The init structure generated as<YourStructureName>Init
. So, you can usefrom(...)
orinto()
functions from it.
Marking the derive attribute on your structures:
// Import it
use Builder;
// And use it on your structs
Using the builder pattern on your structures
// Creating instances
// Option #1:
let s1 : MyStructure = new;
// Option #2 (named arguments emulation):
let s2 : MyStructure = MyStructureInit .into;
// Working with instances
let updated =
s1.clone
.with_opt_field1 // for Option<> fields you specify a bare argument
.without_opt_field2 // you can reset Option<> if you need it
.opt_opt_field1
Defaults
While you're free to use the Rust Default
on your own structs or on auxiliary init structs
this lib intentionally ignores this approach and gives you an auxiliary default
attribute
to manage this like:
let my_struct : StructWithDefault = from;
Licence
Apache Software License (ASL)
Author
Abdulla Abdurakhmanov