Skip to content

required ​

Applies to: struct fields function arguments method arguments

Disables Option<T> special handling, makes the member required.

TIP

This attribute is also configurable via the top-level #[builder(on(...))]. Currently, it can only be used with the _ type pattern and as the first on(...) clause.

Examples ​

rust
use bon::Builder;

#[derive(Builder)]
struct Example {
    #[builder(required)]
    required: Option<u32>,

    optional: Option<u32>,
}

Example::builder()
    .required(Some(2))
    .optional(2)
    .build();
rust
use bon::builder;

#[builder]
fn example(
    #[builder(required)]
    required: Option<u32>,

    optional: Option<u32>,
) {}

example()
    .required(Some(2))
    .optional(2)
    .call();
rust
use bon::bon;

struct Example;

#[bon]
impl Example {
    #[builder]
    fn example(
        #[builder(required)]
        required: Option<u32>,

        optional: Option<u32>,
    ) {}
}

Example::example()
    .required(Some(2))
    .optional(2)
    .call();

Notice the difference:

Member nameSettersComment
requiredrequired(Option<u32>)Setter is required to call
optionaloptional(u32)
maybe_optional(Option<u32>)
Setters are optional to call