Expand description
This crate provides a derive-macro to generate the builder pattern for a struct.
The builder implementation contains a method for each field of the struct, ignoring fields with
the #[skip] attribute.
Each field to generate a method for must be of type Option
§Examples
use build_it::Builder;
#[derive(Default, Builder)]
struct MyAwesomeStruct {
name: Option<String>,
pub age: Option<u32>,
#[build_it(skip)]
address: String,
/// The `#[build_it(rename = "new_name")]` attribute can be used to rename the builder
/// method. In this case, the builder method will be called `new_name` instead of
/// `renamed`:
/// `let builder = MyAwesomeStruct::default().new_name("Alice".to_string());`
#[build_it(rename = "new_name")]
renamed: Option<String>,
/// The `#[build_it(into)]` attribute can be used to allow the builder method to accept
/// types that can be converted into the field type. In this case, the builder method will
/// accept a `&str` instead of a `String`:
/// `let builder = MyAwesomeStruct::default().name_into("Alice");`
#[build_it(into)]
name_into: Option<String>,
#[build_it(skip)]
// NOTE: While the `#[skip]` attribute is still supported, it is deprecated in favor of
// the `#[build_it(skip)]` attribute.
pub phone: Option<String>,
}
let builder = MyAwesomeStruct::default()
.name("Alice".to_string())
.age(42);
// Note that `address` and `phone` do not have builder methods because of the #[skip]
// attribute.
assert_eq!(builder.name, Some("Alice".to_string()));
assert_eq!(builder.age, Some(42));
// These fields are skipped, so they're value will still be the default value.
assert_eq!(builder.address, String::default());
assert_eq!(builder.phone, None);
The generated builder methods will also display the field’s documentation:
use build_it::Builder;
#[derive(Default, Builder)]
struct MyAwesomeStruct {
/// Name of the person
name: Option<String>,
/// Age of the person
age: Option<u32>,
}
This will generate the following builder methods:
impl MyAwesomeStruct {
/// Name of the person
pub fn name(mut self, name: String) -> Self {
self.name = Some(name);
self
}
/// Age of the person
pub fn age(mut self, age: u32) -> Self {
self.age = Some(age);
self
}
}
Derive Macros§
- Builder
- Derive the builder pattern for a struct.