Derive a builder from constructors/methods using the typesafe builder pattern!
Use this if your constructors/method has: * Optional parameters. * A large number of parameters. * Collections parameters.
Add the dependency to your Cargo.toml
toml
[dependencies]
buildstructor = "*"
impl
with #[buildstructor::buildstructor]
.impl
with #[builder]
.```rust pub struct MyStruct { sum: usize, }
impl MyStruct { #[builder] fn new(a: usize, b: usize) -> MyStruct { Self { sum: a + b } }
#[builder(entry = "more", exit = "add")]
fn add_more(&mut self, c: usize, d: usize, e: Option<usize>) {
self.sum += c + d + e.unwrap_or(3);
}
}
fn main() { let mut mine = MyStruct::builder().a(2).b(3).build(); assert_eq!(mine.sum, 5);
mine.more().c(1).d(2).add();
assert_eq!(mine.sum, 11);
} ```
The difference between this and other builder crates is that constructors/methods** 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.
Advantages:
Option
param in your fn
and default as normal.async
constructors derives async
builders.Result
) derives fallible builders.Vec
, Deque
, Heap
, Set
, Map
support. Add single or multiple items.self
, &self
and &mut self
are supported.This crate is heavily inspired by the excellent typed-builder crate. It is a good alternative to this crate and well worth considering.
All of these recipes and more can be found in the examples directory
Just write your rust code as usual and annotate the constructor impl with [builder]
Builders can be generated on methods that have no receiver.
Configuration:
* entry
defaults based on fn
name:
* new
=> builder
* <name>_new
=> <name>_builder
* <anything_else>
=> cannot be defaulted and must be specified.
* exit
defaults to build
```rust struct MyStruct { simple: usize }
impl MyStruct { #[builder] fn new(simple: usize) -> MyStruct { Self { simple } } #[builder] fn trynew(simple: usize) -> MyStruct { Self { simple } } #[builder(entry = "random", exit = "create")] fn dorandom(simple: usize) -> MyStruct { Self { simple } } }
fn main() { let mine = MyStruct::builder().simple(2).build(); assert_eq!(mine.simple, 2);
let mine = MyStruct::try_builder().simple(2).build();
assert_eq!(mine.simple, 2);
let mine = MyStruct::random().simple(2).create();
assert_eq!(mine.simple, 2);
} ```
Builders can be generated on methods that take self
, &self
and &mut self
as a parameter.
Configuration:
* entry
cannot be defaulted and must be specified.
* exit
defaults to call
```rust use buildstructor::buildstructor;
pub struct MyStruct;
impl MyStruct { #[builder(entry = "query")] fn do_query(self, _simple: String) -> bool { true }
#[builder(entry = "query_ref", exit = "stop")]
fn do_query_ref(&self, _simple: String) -> bool {
true
}
#[builder(entry = "query_ref_mut", exit = "go")]
fn do_query_ref_mut(&mut self, _simple: String) -> bool {
true
}
}
fn main() { MyStruct::default().query().simple("3".to_string()).call(); // self
let mine = MyStruct::default();
mine.query_ref().simple("3".to_string()).stop(); // &self
let mut mine = MyStruct::default();
mine.query_ref_mut().simple("3".to_string()).go(); // &mut self
} ```
Fields that are Option
will also be optional in the builder. You should do defaulting in your constructor.
```rust struct MyStruct { param: usize }
impl MyStruct {
#[builder]
fn new(param: Option
fn main() { let mine = MyStruct::builder().param(2).build(); asserteq!(mine.param, 2); let mine = MyStruct::builder().andparam(Some(2)).build(); asserteq!(mine.param, 2); let mine = MyStruct::builder().build(); asserteq!(mine.param, 3); } ```
Note that if a field is an Option
or collection then if a user forgets to set it a compile error will be generated.
Types automatically have into conversion if: * the type is not a scalar. * the type has no generic parameters. (this may be relaxed later) * the type is a generic parameter from the impl or constructor method.
This is useful for Strings, but also other types where you want to overload the singular build method. Create an enum that derives From for all the types you want to support and then use this type in your constructor.
You can use generics as usual in your constructor. However, this has the downside of not being able to support optional fields.
```rust
struct MyStruct {
param: String
}
impl MyStruct {
#[builder]
fn new
fn main() { let mine = MyStruct::builder().param("Hi").build(); assert_eq!(mine.param, "Hi"); } ```
To create an async
builder just make your constructor async
.
```rust struct MyStruct { param: usize }
impl MyStruct { #[builder] async fn new(param: usize) -> MyStruct { Self { param } } }
async fn main() { let mine = MyStruct::builder().param(2).build().await; assert_eq!(mine.param, 2); } ```
To create a fallible builder just make your constructor fallible using Result
.
```rust use std::error::Error; struct MyStruct { param: usize }
impl MyStruct {
#[builder]
fn new(param: usize) -> Result
fn main() { let mine = MyStruct::builder().param(2).build().unwrap(); assert_eq!(mine.param, 2); } ```
Collections and maps are given special treatment, the builder will add additional methods to build the collection one element at a time.
```rust
struct MyStruct {
addresses: Vec
impl MyStruct {
#[builder]
fn new(addresses: Vec
fn main() { let mine = MyStruct::builder() .address("Amsterdam".tostring()) .address("Fakenham") .addresses(vec!["Norwich".tostring(), "Bristol".tostring()]) .build(); asserteq!(mine.addresses, vec!["Amsterdam".tostring(), "Fakenham".tostring(), "Norwich".tostring(), "Bristol".tostring()]); } ```
Collections are matched by type name:
| Type Name | Method used to insert | |-----------|-----------------------| | ...Buffer | push() | | ...Deque | push() | | ...Heap | push() | | ...Set | insert() | | ...Stack | push() | | ...Map | insert(, ) | | Vec | push() |
If your type does not conform to these patterns then you can use a type alias to trick buildstructor into giving the parameter special treatment.
Use the plural form in your constructor argument and buildstructor
will automatically try to figure out the singular form for individual entry. For instance:
addresses
=> address
In the case that a singular form cannot be derived automatically the suffix _entry
will be used. For instance:
frodo
=> frodo_entry
Adding a singular entry will automatically perform an into conversion if: * the type is not a scalar. * the type has no generic parameters. (this may be relaxed later) * the type is a generic parameter from the impl or constructor method.
This is useful for Strings, but also other types where you want to overload the singular build method. Create an enum that derives From for all the types you want to support and then use this type in your constructor.
There had to be some magic somewhere.
To provide more control over generated builders and allow builders for methods with receivers the top level annotation has changed:
#[buildstructor::builder]
=> #[buildstructor::buildstructor]
#[buildstructor::buildstructor]
#[builder]
PRs welcome!
Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions.