- Notifications
You must be signed in to change notification settings - Fork23
Next-gen compile-time-checked builder generator, named function's arguments, and more!
License
Apache-2.0, MIT licenses found
Licenses found
elastio/bon
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
📖 Guide Book | Narrative introduction |
🔍 API Reference | Attributes API index |
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 themotivational blog post.
You can turn a function with positional parameters into a function with named parameters with#[builder]
.
use bon::builder;#[builder]fngreet(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 includingasync
, fallible, generic functions,impl Trait
, etc.
Many things are customizable with additional attributes described in theAPI reference, but let's see what elsebon
has to offer.
Use#[derive(Builder)]
to generate a builder for a struct.
use bon::Builder;#[derive(Builder)]structUser{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);
Associated methods require#[bon]
on top of the impl block additionally.
The method namednew
generatesbuilder()/build()
methods.
use bon::bon;structUser{id:u32,name:String,}#[bon]implUser{#[builder]fnnew(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 thenew()
method with a signature similar to the struct's fields (more details on theCompatibility page).
All other methods generate{method_name}()/call()
methods.
use bon::bon;structGreeter{name:String,}#[bon]implGreeter{#[builder]fngreet(&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 withoutself
are both supported.
Builders generated bybon
'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 astar on Github ⭐! |
---|
What you've seen above is the first page of the 📖 Guide Book. If you want to learn more, jump to theBasics 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 ofbon
. Both#[derive(Builder)]
on structs and#[builder]
on functions/methods have almost identical attributes API, so the documentation for them is common.
Addbon
to yourCargo.toml
.
[dependencies]bon ="3.5"
You can opt out ofstd
andalloc
cargo features withdefault-features = false
forno_std
environments.
This project was heavily inspired by such awesome crates asbuildstructor
,typed-builder
andderive_builder
. This crate was designed with many lessons learned from them.
Seealternatives for comparison.
Some notable users:
If you can't figure something out, consult the docs and maybe use the🔍 Search
bar on ourdocs website. You may also create an issue or a discussion on theGithub repository for help or write us a message onDiscord.
Discord | Here you can leave feedback, ask questions, report bugs, or just write "thank you". |
X (Twitter) | Profile of the maintainer. There are only posts aboutbon and Rust in general here. |
Unless you explicitly state otherwise, any contribution intentionally submittedfor inclusion in the work by you, as defined in the Apache-2.0 license, shall bedual licensed as above, without any additional terms or conditions.
About
Next-gen compile-time-checked builder generator, named function's arguments, and more!