bon
is a Rust crate for generating compile-time-checked builders for functions and structs. It also provides idiomatic partial application with optional and named parameters for functions and methods.
Visit the guide for a complete overview of the crate.
Quick examples
Builder for a free function
You can turn a function with positional parameters into a function with named parameters just by placing the #[builder]
attribute on top of it.
use builder;
let greeting = greet
.name
.level // <- setting `level` is optional, we could omit it
.call;
assert_eq!;
Builder for an associated method
For associated methods you also need to add the #[bon]
macro on top of the impl block.
use bon;
// <- this attribute is required on impl blocks that contain `#[builder]`
// The method named `new` generates `builder()/build()` methods
let user = builder
.id
.name
.build;
// All other methods generate `method_name()/call()` methods
let greeting = user
.greet
.target
// `level` is optional, we can omit it here
.call;
assert_eq!;
assert_eq!;
assert_eq!;
Builder for a struct
The #[derive(Builder)]
macro generates a builder for a struct.
use Builder;
let user = builder
.name
// `level` is optional, we could omit it here
.level
// call setters in any order
.is_admin
.build;
assert_eq!;
assert_eq!;
assert!;
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 🐱!