#[derive(builder)]
{
// Attributes available to this derive:
#[new]
}
Expand description
Generates appropriate builder methods for a struct.
This assumes that the struct itself acts like a builder.
This derive macro also adds a #[new] helper attribute. If this is added to the struct, a new
function is also generated with a where Self: Default bound.
The builder methods generated for each field will have that field’s visibility: private fields will have private methods, etc.
§Examples
#[derive(Default, builder)]
#[new]
struct Example {
pub x: i32,
pub y: i32,
}This will derive the following implementations:
impl Example {
/// Creates a new `Example`.
///
/// This is equivalent to <code>Example::[default()]</code>.
///
/// [default()]: Default::default()
pub fn new() -> Self
where
Self: Default,
{
Self::default()
}
/// Sets `x` to the given value.
pub fn x(mut self, x: i32) -> Self {
self.x = x;
self
}
/// Sets `y` to the given value.
pub fn y(mut self, y: i32) -> Self {
self.y = y;
self
}
}#[derive(builder)] also works on tuple structs (with any number of fields):
#[derive(Default, builder)]
struct Example(pub i32, pub i32);This will derive the following implementations:
impl Example {
/// Sets the first field to the given value.
pub fn first(mut self, first: i32) -> Self {
self.0 = first;
self
}
/// Sets the second field to the given value.
pub fn second(mut self, second: i32) -> Self {
self.1 = second;
self
}
}