bon_macros

Attribute Macro bon

Source
#[bon]
Expand description

Companion macro for builder. You should place it on top of the impl block where you want to define methods with the builder macro.

It provides the necessary context to the builder macros on top of the functions inside of the impl block. You’ll get compile errors without that context.

§Quick example

use bon::bon;

struct User {
    id: u32,
    name: String,
}

#[bon] // <- this attribute is required on impl blocks that contain `#[builder]`
impl User {
    #[builder]
    fn new(id: u32, name: String) -> Self {
        Self { id, name }
    }

    #[builder]
    fn greet(&self, target: &str, level: Option<&str>) -> String {
        let level = level.unwrap_or("INFO");
        let name = &self.name;

        format!("[{level}] {name} says hello to {target}")
    }
}

// The method named `new` generates `builder()/build()` methods
let user = User::builder()
    .id(1)
    .name("Bon".to_owned())
    .build();

// All other methods generate `method_name()/call()` methods
let greeting = user
    .greet()
    .target("the world")
    // `level` is optional, we can omit it here
    .call();

assert_eq!(user.id, 1);
assert_eq!(user.name, "Bon");
assert_eq!(greeting, "[INFO] Bon says hello to the world");

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

For details on this macro see the overview.