Skip to content

Introduce bool shorthand (#[builder(flag)]) #142

@SteelAlloy

Description

@SteelAlloy

Hey there,

Bon is great but it still feels weird to write .property(true) for booleans and I feel that an option to shorten this usage would be a nice addition.

The syntax is just an example of how I would see it implemented :

use bon::Builder;

#[derive(Builder)]
struct User {
    id: u32,
    #[builder(bool)] // add some attribute to a boolean property
    color: bool,
}

And then use it without specifying true :

let user = User::builder()
    .id(1)
    .color() // true
    .build();

For falsy values, one could think of adding the same method with a prefix (no_ by default) :

use bon::Builder;

#[derive(Builder)]
struct User {
    id: u32,
    #[builder(bool, false = "no")] // optional, defaults to "no"
    color: bool,
}

And then :

let user = User::builder()
    .id(1)
    .no_color() // false
    .build();

let user = User::builder()
    .id(1)
    .color() // still valid : true
    .build();

Feedback is welcome, it would greatly improve my builders!

A note for the community from the maintainers

Please vote on this issue by adding a 👍 reaction to help the maintainers with prioritizing it. You may add a comment describing your real use case related to this issue for us to better understand the problem domain.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions