elastio/bon

Rustbon-rs.com

Next-gen compile-time-checked builder generator, named function's arguments, and more!

asynchronousbuilderbuilder-patternbuildersconstructorconstructorsdata-structuresderivederive-macromacromacrosrust
Sterne-Wachstum
Sterne
2.1k
Forks
45
Wochenwachstum
+5
Issues
28
1k2k
Sept. 25Jan. 26Mai 26Sept. 26
Artefaktecrates.io
README
bon home
github crates.io docs.rs docs.rs

📖 Guide Book Narrative introduction
🔍 API Reference Attributes API index

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.10"

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.

Past Supporters

Big thanks to bon's past financial supporters ❤️


Kindness

Ethan Skowronski

Julius Lungys

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.
Ähnliche Repositories
tokio-rs/tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...

Rustcrates.iolibraryMIT Licenserustasynchronous
tokio.rs
33.1k3.2k
libuv/libuv

Cross-platform asynchronous I/O

ClibraryMIT Licenseasynchronousio
libuv.org
27.2k3.9k
tornadoweb/tornado

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

PythonPyPIlibraryApache License 2.0pythonasynchronous
tornadoweb.org
22.2k5.6k
ktorio/ktor

Framework for quickly creating connected applications in Kotlin with minimal effort

KotlinlibraryApache License 2.0kotlinweb-framework
ktor.io
14.5k1.3k
nmap/nmap

Nmap - the Network Mapper. Github mirror of official SVN repository.

COtherc-plus-pluslua
svn.nmap.org
13.5k2.9k
walkor/workerman

An asynchronous event driven PHP socket framework. Supports HTTP, Websocket, SSL and other custom protocols.

PHPPackagistlibraryMIT Licensewebsockettimer
workerman.net
11.5k2.2k
panjf2000/gnet

🚀 gnet is a high-performance, lightweight, non-blocking, event-driven networking framework written in pure Go.

GoGo ModuleslibraryApache License 2.0event-drivenevent-loop
gnet.host
11.2k1.1k
alibaba/transmittable-thread-local

📌 a missing Java std lib(simple & 0-dependency) for framework/middleware, provide an enhanced InheritableThreadLocal that transmits values between threads even using thread pooling components.

JavaMavenlibraryApache License 2.0javathreadlocal
github.com/alibaba/transmittable-thread-local
8.3k1.7k
final-form/react-final-form

🏁 High performance subscription-based form state management for React

JavaScriptnpmMIT Licensereactform
final-form.org/react
7.4k497
mher/flower

Real-time monitor and web admin for Celery distributed task queue

PythonPyPIOthercelerytask-queue
flower.readthedocs.io
7.2k1.2k
tokio-rs/mio

Metal I/O library for Rust.

Rustcrates.iolibraryMIT Licenserustnon-blocking
7.1k868
marlonrichert/zsh-autocomplete

🤖 Real-time type-ahead completion for Zsh. Asynchronous find-as-you-type autocompletion.

ShellMIT Licensezshcompletion
6.7k202