Skip to content

Documenting

In regular Rust, it's not possible to place doc comments on function arguments. But with #[builder] it is. Documentation written on the arguments will be placed on the generated setter methods.

Example:

rust
use bon::builder;

/// Function that returns a greeting special-tailored for a given person
#[builder]
fn greet(
    /// Name of the person to greet.
    ///
    /// **Example:**
    /// ```
    /// greet().name("John");
    /// ```
    name: &str,

    /// Age expressed in full years passed since the birth date.
    age: u32
) -> String {
    format!("Hello {name} with age {age}!")
}
How does this work? 🤔

This works because Rust compiler checks for invalid placement of #[doc = ...] attributes only after the macro expansion stage. #[builder] removes the docs from the function's arguments in the expanded code, and instead moves them to the docs on setter methods.

When #[derive(Builder)] is placed on top of a struct, then documentation on the struct fields will be copied to the docs on the setter methods.

Custom doc attributes

You can override documentation on other items generated by builder macros. There are multiple attributes accepting a doc { ... } block.

rust
use bon::Builder;

#[derive(Builder)]
#[builder(
    builder_type(doc {
        /// Custom docs on the builder struct itself
    }),
    start_fn(doc {
        /// Custom docs on the starting function
    }),
    // ...
)]
struct Example {}

You can document the following items this way:

AttributeDocumentation target
builder_typeBuilder struct
start_fnStarting function
finish_fnFinishing function
state_modBuilder state API module (more details in Typestate API)
settersCustom docs for setters. Prevents copying them from the field/argument

Positional members

Documentation comments are allowed on positional members. However, since there are no separate setter methods generated for them, the docs on these members will not be copied anywhere, and thus they won't appear in rustdoc. Instead, it's recommended to write documentation for these members on the top level of the struct or function.