Skip to content

elastio/bon

Repository files navigation

bon home

github crates.io docs.rs

bon is a Rust crate for generating compile-time-checked builders for functions and structs.

Visit the guide for a complete overview of the crate.

Quick examples

bon can turn a function with positional parameters into a function with "named" parameters via a builder. It's as easy as placing the #[builder] attribute on top of it.

use bon::builder;

#[builder]
fn greet(name: &str, age: u32) -> String {
    format!("Hello {name} with age {age}!")
}

let greeting = greet()
    .name("Bon")
    .age(24)
    .call();

assert_eq!(greeting, "Hello Bon with age 24!");

You can also use the #[builder] attribute with structs and associated methods:

use bon::{bon, builder};

#[builder]
struct User {
    id: u32,
    name: String,
}

#[bon]
impl User {
    #[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}")
    }
}

let user = User::builder()
    .id(1)
    .name("Bon".to_owned())
    .build();

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");

See the guide for the rest.


If you like the idea of this crate and want to say "thank you" or "keep doing this" consider giving us a star ⭐ on Github. Any support and contribution are appreciated 🐱!

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
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 dual licensed as above, without any additional terms or conditions.