A derive macros to support a builder pattern for Rust:
- Everything except Option<>
fields and explicitly defined default
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).
Add this to your Cargo.toml
:
toml
[dependencies]
rsb_derive = "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 for Option<>
input argument)
- <field_name>/reset/mopt_<field_name>
: mutable setters for fields (mopt
is an additional setter for Option<>
input argument)
- new
: factory method with required fields as arguments
- From<>
instance from an an auxiliary init struct definition with only required fields.
The init structure generated as <YourStructureName>Init
. So, you can use from(...)
or into()
functions from it.
```rust // Import it use rsb_derive::Builder;
// And use it on your structs
struct MyStructure {
pub reqfield1: String,
pub reqfield2: i32,
pub optfield1: Option
```rust // Creating instances
// Option #1: let s1 : MyStructure = MyStructure::new( "hey".into(), 0);
// Option #2 (named arguments emulation): let s2 : MyStructure = MyStructureInit { reqfield1 : "hey".into(), reqfield2 : 0 }.into();
// Working with instances
let updated =
s1.clone()
.withoptfield1("hey".into()) // for Option<> fields you specify a bare argument
.withoutoptfield2() // you can reset Option<> if you need it
.optoptfield1(Some(("hey".into())) // you can use opt
// All together example
let s1 : MyStructure = MyStructure::from( MyStructureInit { reqfield1 : "hey".into(), reqfield2 : 0 } ) .withoptfield1("hey".into()) .withoptfield2(10);
// Mutable example (in case you really need it) let mut s1 : MyStructure = MyStructure::from( MyStructureInit { reqfield1 : "hey".into(), reqfield2 : 0 } );
s1
.optfield1("hey".into()) // no prefix with for mutable setter
.optfield2(10)
.field2(15)
.resetoptfield2(); // mutable reset function for optional fields
```
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:
```rust
struct StructWithDefault { pub reqfield1: String, #[default="10"] pub reqfield2: i32, // default here make this field behave like optional
pub opt_field1: Option<String>,
#[default="Some(11)"]
pub opt_field2: Option<i32> // default works also on optional fields
}
let mystruct : StructWithDefault = StructWithDefault::from( StructWithDefaultInit { reqfield1 : "test".into() } ); ```
Apache Software License (ASL)
Abdulla Abdurakhmanov