Skip to content

builder_type ​

Applies to: structs functions methods

Overrides name, visibility and docs for the builder struct.

Short syntax configures just the name.

attr
#[builder(builder_type = CustomName)]

Long syntax provides more flexibility. All keys are optional.

attr
#[builder(
    builder_type(
        name = CustomName,
        vis = "pub(crate)",
        doc {
            /// Custom docs
        }
    )
)]

name ​

The default name for the builder struct is chosen according to the following rules:

SyntaxDefault
struct T{T}Builder
Associated fn T::new/builder(){T}Builder
Associated fn T::fn_name(){T}{FnName}Builder
Free fn fn_name(){FnName}Builder

vis ​

The visibility must be enclosed with quotes. Use "" or "pub(self)" for private visibility.

The default visibility is the same as the visibility of the underlying struct or fn.

doc ​

Simple documentation is generated by default. The syntax of this attribute expects a block with doc comments.

attr
doc {
    /// Doc comments
}

Examples ​

rust
use bon::Builder;

#[derive(Builder)]
#[builder(builder_type = MyBuilder)] 
struct Brush {}

let builder: MyBuilder = Brush::builder();
rust
use bon::builder;

#[builder(builder_type = MyBuilder)] 
fn brush() {}

let builder: MyBuilder = brush();
rust
use bon::bon;

struct Brush;

#[bon]
impl Brush {
    #[builder(builder_type = MyBuilder)] 
    fn new() -> Self {
        Self
    }
}

let builder: MyBuilder = Brush::builder();

You'll usually want to override the builder type name when you already have such a name in scope. For example, if you have a struct and a function with the same name both annotated with #[derive(Builder)] and #[builder]:

rust
use bon::{builder, Builder};

#[derive(Builder)] 
struct Brush {}

#[builder] 
fn brush() {}

// `BrushBuilder` builder type name was generated for both
// the struct and the function. This is a compile error
let builder: BrushBuilder = Brush::builder();
let builder: BrushBuilder = brush();
rust
use bon::{builder, Builder};

#[derive(Builder)]
#[builder(builder_type = MyBuilder)] 
struct Brush {}

#[builder]
fn brush() {}

// Now builder types are named differently
let builder: MyBuilder = Brush::builder();
let builder: BrushBuilder = brush();