bon_macros

Derive Macro Builder

Source
#[derive(Builder)]
{
    // Attributes available to this derive:
    #[builder]
}
Expand description

Derives a builder for the struct it’s placed on.

§Quick example

Add a #[derive(Builder)] attribute to your struct to generate a builder() method for it.

use bon::{bon, builder, Builder};

#[derive(Builder)]
struct User {
    name: String,
    is_admin: bool,
    level: Option<u32>,
}

let user = User::builder()
    .name("Bon".to_owned())
    // `level` is optional, we could omit it here
    .level(24)
    // call setters in any order
    .is_admin(true)
    .build();

assert_eq!(user.name, "Bon");
assert_eq!(user.level, Some(24));
assert!(user.is_admin);

The builder never panics. Any mistakes such as missing required fields or setting the same field twice will be reported as compile-time errors.

See the full documentation for more details: