How to Implement a Builder Pattern with Derive Macros

Implement a Builder pattern in Rust by adding the buildstructor crate and using the #[derive(Builder)] attribute on your struct.

Use the buildstructor crate to generate a Builder pattern implementation via a custom derive macro. Add the dependency to your Cargo.toml and apply the #[derive(Builder)] attribute to your struct. The macro generates a Builder type with fluent setter methods and a build() function.

use buildstructor::Builder;

#[derive(Builder)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect = Rectangle::builder()
        .width(30)
        .height(50)
        .build();
}