MCPcopy Index your code
hub / github.com/elastio/bon

github.com/elastio/bon @v3.9.3

Chat with this repo
repository ↗ · DeepWiki ↗ · release v3.9.3 ↗ · + Follow
1,315 symbols 2,326 edges 199 files 56 documented · 4%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

bon home

<a href="https://github.com/elastio/bon"><img
    alt="github"
    src="https://img.shields.io/badge/github-elastio/bon-228b22?style=for-the-badge&labelColor=555555&logo=github"
    height="25"
/></a>
<a href="https://crates.io/crates/bon"><img
    alt="crates.io"
    src="https://img.shields.io/crates/v/bon.svg?style=for-the-badge&color=e37602&logo=rust"
    height="25"
/></a>
<a href="https://docs.rs/bon/latest/bon/"><img
    alt="docs.rs"
    src="https://img.shields.io/badge/docs.rs-bon-3b74d1?style=for-the-badge&labelColor=555555&logo=docs.rs"
    height="25"
/></a>
    <a href="https://docs.rs/bon/latest/bon/"><img
    alt="docs.rs"
    src="https://img.shields.io/badge/MSRV-1.59.0-b83fbf?style=for-the-badge&labelColor=555555&logo=docs.rs"
    height="25"
/></a>











<table>
    <tbody>
        <tr>
            <td><a href="https://bon-rs.com/guide/overview">📖 Guide Book</a></td>
            <td>Narrative introduction</td>
        </tr>
        <tr>
            <td><a href="https://bon-rs.com/reference/builder">🔍 API Reference</a></td>
            <td>Attributes API index</td>
        </tr>
    </tbody>
</table>

Overview

bon is a Rust crate for generating compile-time-checked builders for structs and functions. It also provides idiomatic partial application with optional and named parameters for functions and methods.

If you wonder "Why would I use builders?", see the motivational blog post.

Function Builder

You can turn a function with positional parameters into a function with named parameters with #[builder].

use bon::builder;

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

    format!("Hello {name}! Your level is {level}")
}

let greeting = greet()
    .name("Bon")
    .level(24) // <- setting `level` is optional, we could omit it
    .call();

assert_eq!(greeting, "Hello Bon! Your level is 24");

Any syntax for functions is supported including async, fallible, generic functions, impl Trait, etc.

Many things are customizable with additional attributes described in the API reference, but let's see what else bon has to offer.

Struct Builder

Use #[derive(Builder)] to generate a builder for a struct.

use bon::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);

Method Builder

Associated methods require #[bon] on top of the impl block additionally.

Method new

The method named new generates builder()/build() methods.

use bon::bon;

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

#[bon]
impl User {
    #[builder]
    fn new(id: u32, name: String) -> Self {
        Self { id, name }
    }
}

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

assert_eq!(user.id, 1);
assert_eq!(user.name, "Bon");

#[derive(Builder)] on a struct generates builder API that is fully compatible with placing #[builder] on the new() method with a signature similar to the struct's fields (more details on the Compatibility page).

Other Methods

All other methods generate {method_name}()/call() methods.

use bon::bon;

struct Greeter {
    name: String,
}

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

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

let greeter = Greeter { name: "Bon".to_owned() };

let greeting = greeter
    .greet()
    .target("the world")
    // `prefix` is optional, omitting it is fine
    .call();

assert_eq!(greeting, "[INFO] Bon says hello to the world");

Methods with or without self are both supported.

No Panics Possible

Builders generated by bon's macros use the typestate pattern to ensure all required parameters are filled, and the same setters aren't called repeatedly to prevent unintentional overwrites. If something is wrong, a compile error will be created.

⭐ Don't forget to give our repo a star on Github ⭐!

What's Next?

What you've seen above is the first page of the 📖 Guide Book. If you want to learn more, jump to the Basics section. And remember: knowledge is power 🐱!

Feel free to jump to code and use the #[builder] and #[derive(Builder)] once you've seen enough docs to get started.

The 🔍 API Reference will help you navigate the attributes once you feel comfortable with the basics of bon. Both #[derive(Builder)] on structs and #[builder] on functions/methods have almost identical attributes API, so the documentation for them is common.

Installation

Add bon to your Cargo.toml.

[dependencies]
bon = "3.9"

You can opt out of std and alloc cargo features with default-features = false for no_std environments.

See alternatives for comparison.

Getting Help

If you can't figure something out, consult the docs and maybe use the 🔍 Search bar on our docs website. You may also create an issue or a discussion on the Github repository for help or write us a message on Discord.

Socials

Discord Here you can leave feedback, ask questions, report bugs, etc.

Acknowledgments

This project was heavily inspired by such awesome crates as buildstructor, typed-builder and derive_builder. This crate was designed with many lessons learned from them.

Supporters

Big thanks to bon's current financial supporters ❤️

Julius Lungys\ $1/month

Past Supporters

Big thanks to bon's past financial supporters ❤️

\ Kindness

Ethan Skowronski

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.

Extension points exported contracts — how you extend this code

MyTrait (Interface)
(no doc) [4 implementers]
bon/tests/integration/builder/generics_setters.rs
FinishFnBody (Interface)
(no doc) [2 implementers]
bon-macros/src/builder/builder_gen/models.rs
Sealed (Interface)
(no doc) [2 implementers]
bon/src/__/mod.rs
Trait (Interface)
(no doc) [3 implementers]
bon/tests/integration/builder/generics.rs
VecExt (Interface)
(no doc) [1 implementers]
bon-macros/src/util/vec.rs
IsSet (Interface)
(no doc) [1 implementers]
bon/src/builder_state.rs
MyTrait (Interface)
(no doc) [2 implementers]
bon/tests/integration/ui/compile_fail/generics_setters/qualified_path.rs
IdentExt (Interface)
(no doc) [1 implementers]
bon-macros/src/util/ident.rs

Core symbols most depended-on inside this repo

builder
called by 149
bon-macros/src/lib.rs
assert_match_types
called by 47
bon-macros/src/util/ty/match_types.rs
into_iter
called by 40
bon-macros/src/normalization/syntax_variant.rs
reject_attrs
called by 32
bon-macros/src/parsing/mod.rs
assert_not_match_types
called by 29
bon-macros/src/util/ty/match_types.rs
recurse
called by 25
bon-macros/src/error/mod.rs
join
called by 12
bon-macros/src/util/iterator.rs
assert_unsupported
called by 11
bon-macros/src/util/ty/match_types.rs

Shape

Class 445
Function 442
Method 388
Interface 22
Enum 18

Languages

Rust100%

Modules by API surface

benchmarks/compilation/src/structs_100_fields_10.rs100 symbols
bon/tests/integration/builder/attr_bon.rs31 symbols
bon/tests/integration/builder/generics.rs23 symbols
bon/tests/integration/ui/compile_fail/attr_with.rs21 symbols
bon/tests/integration/ui/compile_fail/attr_derive.rs20 symbols
bon-macros/src/util/ty/match_types.rs20 symbols
bon-macros/src/normalization/lifetimes.rs20 symbols
bon-macros/src/builder/builder_gen/setters/mod.rs20 symbols
bon/tests/integration/builder/attr_into_future.rs19 symbols
bon-macros/tests/snapshots/setters_docs_and_vis.rs19 symbols
bon/tests/integration/ui/compile_fail/attr_builder.rs18 symbols
bon-macros/src/builder/builder_gen/models.rs17 symbols

For agents

$ claude mcp add bon \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact