Stop Writing Boilerplate Builders! Use `bon` Instead
Stop Writing Boilerplate Builders! Use bon Instead
What if I told you that every hour you've spent hand-rolling builder patterns in Rust was completely wasted? That the tedious dance of Option<T> fields, the build() methods that panic at runtime, the endless copy-paste of setter after setter—all of it could vanish with a single attribute macro?
Here's the painful truth most Rust developers learn the hard way: the builder pattern is essential, but implementing it manually is a productivity killer. You've been there. A struct with eight fields becomes twelve lines of boilerplate. Then twenty-four. Then you add validation logic, and suddenly your "simple" builder is 200 lines of fragile code. Worse, you only discover missing required fields when your program panics at runtime—not when you compile.
But what if your compiler could catch builder misuse before your code ever ran? What if you could turn any function into a named-argument API with zero effort? What if the solution was already sitting in elastio/bon, quietly becoming the most-starred builder generator in the Rust ecosystem?
Welcome to bon—the next-generation compile-time-checked builder generator that's making handwritten builders obsolete.
What is bon?
bon is a Rust procedural macro crate developed by Elastio that generates compile-time-checked builders for structs, functions, and methods. Unlike traditional builder libraries that rely on runtime validation (and potentially panics), bon leverages Rust's type system through the typestate pattern to enforce correctness at compile time.
The crate's full name—"bon"—carries a playful nod to "bon appetit" for your Rust code, but the technology behind it is dead serious. At its core, bon solves three interconnected problems that have plagued Rust developers for years:
- The struct builder boilerplate problem: Deriving
Buildereliminates hand-written setter methods - The named function arguments problem: The
#[builder]macro transforms positional parameters into fluent, named APIs - The compile-time safety problem: Typestate ensures required fields are set, duplicates are prevented, and errors surface during compilation—not production
bon is trending now because it represents a generational leap over earlier crates like derive_builder, typed-builder, and buildstructor. Where those tools offered partial solutions, bon unifies them into a cohesive, zero-cost abstraction with an MSRV of just Rust 1.59.0.
The crate currently sits at version 3.9 on crates.io, with comprehensive documentation at bon-rs.com and an active Discord community. Its dual Apache-2.0/MIT licensing makes it suitable for any project, commercial or open source.
Key Features That Make bon Insane
Let's dissect what makes bon genuinely transformative for Rust development:
Compile-Time Typestate Validation
This is bon's secret weapon. The generated builders use generic type parameters to track which fields have been set. Attempt to call .build() before setting a required field? Compile error. Try to call .name() twice? Compile error. The type system becomes your enforcer, eliminating entire classes of runtime bugs.
Function-Level Builder Generation
No other mainstream crate does this elegantly. The #[builder] attribute on functions creates a fluent API from positional parameters. This enables partial application and named arguments—features Rust deliberately omits from its core syntax. Your functions become self-documenting through their call sites.
Full Async, Generic, and impl Trait Support
bon doesn't cripple your API design. async functions, generics, impl Trait arguments, fallible functions with Result returns—all are natively supported. The macro expansion correctly preserves complex signatures without forcing artificial constraints.
Method Builders with #[bon]
Associated methods require special handling because of self. The #[bon] attribute on impl blocks, combined with #[builder] on individual methods, generates context-aware builders. Methods named new get .builder()/.build(), while others get .{method_name}()/.call()—semantic conventions that match developer intuition.
no_std Compatibility
With default-features = false, bon strips its std and alloc dependencies for embedded and kernel contexts. This isn't an afterthought; it's a first-class configuration.
Zero Runtime Overhead
All magic happens at compile time. The generated code is as efficient as hand-written builders—often more so, since the macro authors have optimized patterns you might overlook.
Real-World Use Cases Where bon Dominates
1. Configuration Structs with Many Optional Fields
Database connection pools, HTTP clients, and service configurations notoriously accumulate optional parameters. A hand-written builder for reqwest::Client equivalents becomes unwieldy fast. #[derive(Builder)] collapses this to the struct definition itself, with Option<T> fields automatically handled as optional setters.
2. Domain-Driven Design: Entity Construction
In DDD, entities often have complex construction rules. A User entity might require an email but optionally accept a display name, role, and metadata. bon enforces these business rules through types—impossible to instantiate an invalid User at the compiler level.
3. API Client SDKs with Fluent Interfaces
When building SDKs for REST APIs, method chaining improves discoverability. bon generates this pattern from simple function definitions, letting you ship ergonomic APIs without maintaining builder boilerplate alongside your endpoint logic.
4. Test Fixture Builders
Tests often need variations of the same struct with minor changes. bon builders compose beautifully with Default implementations, letting you write User::builder().name("test").build() instead of User { name: "test".into(), ..Default::default() }—more explicit, more flexible, and type-safe.
Step-by-Step Installation & Setup Guide
Getting bon running takes under two minutes. Here's the complete workflow:
Add to Cargo.toml
[dependencies]
bon = "3.9"
For no_std environments, explicitly disable default features:
[dependencies]
bon = { version = "3.9", default-features = false }
Import Macros
In your Rust source files, import the macros you'll use:
// For function and method builders
use bon::{builder, bon, Builder};
Verify Your Rust Version
Ensure your toolchain meets the MSRV:
rustc --version # Should be >= 1.59.0
If needed, update via rustup:
rustup update stable
IDE Integration
The generated builders are fully visible to rust-analyzer after expansion. For the best experience, ensure your editor runs cargo check on save—type errors in builder chains will surface immediately with precise diagnostics pointing to missing or duplicate setters.
REAL Code Examples from elastio/bon
Let's examine actual code from the repository, with detailed breakdowns of what each example demonstrates.
Example 1: Function Builder with Named Arguments
This is bon's headline feature—transforming positional functions into named, fluent APIs:
use bon::builder;
// The #[builder] macro generates a builder struct and setter methods
// for each parameter. 'name' is required; 'level' is Option<u32>,
// so it's automatically optional in the builder.
#[builder]
fn greet(name: &str, level: Option<u32>) -> String {
let level = level.unwrap_or(0);
format!("Hello {name}! Your level is {level}")
}
// The builder API: no positional arguments, no confusion about
// parameter order. Each setter returns the builder for chaining.
let greeting = greet()
.name("Bon") // Required: must be called before .call()
.level(24) // Optional: could be omitted
.call(); // Executes the actual function
assert_eq!(greeting, "Hello Bon! Your level is 24");
What's happening here? The #[builder] macro rewrites greet to return a builder state that requires .name() before .call(). The level parameter's Option<u32> type signals to the macro that this setter can be skipped. The .call() method finalizes construction and invokes the original function logic. This pattern eliminates the "what was the third parameter again?" problem entirely.
Example 2: Struct Builder with #[derive(Builder)]
For data structures, derive-based generation keeps your domain model clean:
use bon::Builder;
// Deriving Builder generates a UserBuilder type with methods:
// .name(String), .is_admin(bool), .level(u32), and .build()
#[derive(Builder)]
struct User {
name: String, // Required field: must be set before build()
is_admin: bool, // Required field
level: Option<u32>, // Optional: typestate allows omitting .level()
}
// Setters can be called in ANY order—typestate tracks state,
// not order. This is crucial for maintainability.
let user = User::builder()
.name("Bon".to_owned())
.level(24) // Optional, but we choose to set it
.is_admin(true) // Required, called after level (order irrelevant)
.build(); // Returns User, guaranteed complete
assert_eq!(user.name, "Bon");
assert_eq!(user.level, Some(24));
assert!(user.is_admin);
The critical insight: User::builder() returns a type that does not yet have build() available. Only after .name() and .is_admin() are called does the typestate transition to a "complete" state where .build() exists. Try calling .build() early, and you get a clear compiler error: no method named build found for struct UserBuilder<...>.
Example 3: Method Builder for new()
When #[builder] is applied to a method named new, bon generates builder()/build() conventions matching the struct derive pattern:
use bon::bon;
struct User {
id: u32,
name: String,
}
// #[bon] on the impl block enables #[builder] on methods within
#[bon]
impl User {
// #[builder] here generates User::builder() -> UserBuilder
// with .id(u32), .name(String), and .build() -> User
#[builder]
fn new(id: u32, name: String) -> Self {
Self { id, name }
}
}
// Identical API to #[derive(Builder)] on a struct—intentionally
// compatible for refactoring flexibility
let user = User::builder()
.id(1)
.name("Bon".to_owned())
.build();
assert_eq!(user.id, 1);
assert_eq!(user.name, "Bon");
Why #[bon] on the impl block? Methods have a self receiver that complicates builder generation. The #[bon] attribute provides the macro machinery to handle &self, &mut self, or no self correctly. This two-macro design (#[bon] for the impl, #[builder] for methods) keeps the implementation clean and explicit.
Example 4: Non-new Method Builder
For methods that aren't constructors, bon uses {method_name}()/call() naming:
use bon::bon;
struct Greeter {
name: String,
}
#[bon]
impl Greeter {
// Generates .greet() -> GreeterGreetBuilder with
// .target(&str), .prefix(Option<&str>), and .call() -> String
#[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() };
// The builder captures &self, so it's called on the instance
let greeting = greeter
.greet() // Returns builder bound to &greeter
.target("the world") // Required: must be set before call()
// .prefix("DEBUG") // Optional: omitted here
.call(); // Executes greet(), consuming the builder
assert_eq!(greeting, "[INFO] Bon says hello to the world");
Advanced pattern: The builder captures the &self reference from greeter.greet(), making it available when .call() eventually invokes the method. This is zero-cost—the reference is stored directly in the builder struct, not boxed or dynamically dispatched.
Advanced Usage & Best Practices
Migration Strategy: From Hand-Written to bon
Don't refactor everything at once. Start with your most complex builders—the ones with validation logic and multiple optional fields. bon's typestate often eliminates validation code entirely, since the type system proves correctness.
Customizing with Attributes
The API Reference documents extensive customization: renaming setters, skipping fields, adding custom validation, and controlling visibility. For example, #[builder(field(name = "display_name"))] renames a setter while keeping the struct field as name.
Performance: Zero-Cost Verified
The generated builders are #[inline]-friendly structs with no dynamic allocation. In release builds, LLVM typically optimizes builder chains into direct struct construction—identical to hand-written code.
Error Messages: Your New Best Friend
bon's compile errors are remarkably clear. A missing required field produces: error: no method named build found for struct UserBuilder<false, true>. The false/true type parameters indicate which fields are set—debugging builder state at the type level.
Comparison with Alternatives
| Feature | bon |
derive_builder |
typed-builder |
buildstructor |
|---|---|---|---|---|
| Compile-time required field checking | ✅ Typestate | ❌ Runtime Result |
✅ Typestate | ✅ Typestate |
| Function builders | ✅ Native | ❌ No | ❌ No | ✅ Limited |
Method builders (self) |
✅ Full support | ❌ No | ❌ No | ✅ Limited |
async/impl Trait/generics |
✅ Full | ⚠️ Partial | ⚠️ Partial | ⚠️ Partial |
no_std support |
✅ Yes | ❌ No | ❌ No | ❌ No |
| MSRV | 1.59.0 | 1.56.0 | 1.61.0 | 1.65.0 |
Why bon wins: It's the only crate combining function-level builders, full method support, modern Rust features, and no_std compatibility with a low MSRV. The unified attribute API across structs, functions, and methods reduces cognitive load compared to learning multiple crates.
FAQ
Does bon add runtime overhead?
No. All builder logic resolves at compile time through monomorphization. The generated code is equivalent to hand-written builders—often better optimized due to macro authors' expertise.
Can I use bon with no_std?
Yes. Set default-features = false in your Cargo.toml dependency. This removes std and alloc requirements, suitable for embedded kernels and bare-metal environments.
What happens if I forget a required field?
You get a compile error immediately. The typestate pattern encodes field presence in the builder's type parameters, so .build() only exists when all required fields are set. No runtime panics, no unwrap() anxiety.
Can I call setters multiple times?
Not for the same field—this prevents accidental overwrites. If you need mutable builders, the API reference documents override attributes. The default behavior prioritizes safety over flexibility.
How does bon compare to named arguments RFCs?
Rust has no stable named argument syntax, and proposed RFCs remain contentious. bon solves this today, without language changes, and works on stable Rust back to 1.59.0. It's the pragmatic solution while the ecosystem debates theoretical perfection.
Is bon production-ready?
With version 3.9, extensive documentation, active maintenance by Elastio, and growing adoption in the Rust ecosystem, bon is suitable for production use. The compile-time guarantees actually reduce risk compared to hand-written builders with potential logic errors.
Where do I get help?
The bon-rs.com docs include a search bar and comprehensive guide. For interactive help, join the Discord server or open an issue on GitHub.
Conclusion: The Builder Pattern, Finally Done Right
bon isn't just another builder crate—it's a fundamental reimagining of how Rust developers construct objects and invoke functions. By pushing validation from runtime to compile time, it eliminates entire categories of bugs while making APIs more discoverable and ergonomic.
The evidence is in the code: function builders that turn positional parameters into self-documenting fluent interfaces. Struct builders that enforce completeness through types, not panics. Method builders that handle self correctly without boxing or dynamic dispatch. All with no_std support and a 1.59.0 MSRV that doesn't strand legacy projects.
If you're still hand-writing builders in 2024, you're solving a solved problem—with more code, more bugs, and more maintenance burden. The elastio/bon repository represents the accumulated wisdom of the Rust builder ecosystem, distilled into macros that just work.
Your next step: Add bon = "3.9" to your Cargo.toml, slap #[derive(Builder)] on your most painful struct, and watch your boilerplate evaporate. Then explore #[builder] on functions and wonder why you ever tolerated positional arguments. The future of Rust builders is here—and it's compile-time checked.
⭐ Star bon on GitHub and join the growing community of developers who've stopped writing builders and started shipping features.
Explore on the BrightCoding network
Hand-picked resources from our other sites.
Pik: The Sleek Interactive Process Killer Every Developer Needs
Pik revolutionizes process management with interactive fuzzy search, smart filters for ports/arguments/paths, and instant termination. This Rust-powered CLI too...
riyaneel/Tachyon: Sub-100ns Cross-Language IPC for ML and Trading
riyaneel/Tachyon is an Apache 2.0-licensed IPC/RPC primitive achieving 49.9 ns round-trip latency across 8 languages using shared memory and zero-copy semantics...
Stop Wrestling With Nginx Configs! Pingap Is the Rust Proxy You Need
Discover Pingap, the Rust reverse proxy built on Cloudflare's Pingora. Zero-downtime hot reloads, 20+ plugins, insane 147K RPS performance, and TOML configs tha...
Continuez votre lecture
Why Alexandrie is the Ultimate Markdown Note-Taking App
Why CrossPaste is the Ultimate Game Changer for Clipboard Management
Why Chandra is the Ultimate OCR Tool for Handwriting and Tables
Stop Coding Alone: OPC-Skills Gives Your AI Agent Superpowers
Commentaires 0
Aucun commentaire pour l'instant. Soyez le premier à réagir !