idanarye / rust-typed-builder

Compile-time type-checked builder derive
https://crates.io/crates/typed-builder
Apache License 2.0
904 stars 52 forks source link

Build Status Latest Version Rust Documentation

Rust Typed Builder

Creates a compile-time verified builder:

use typed_builder::TypedBuilder;

#[derive(TypedBuilder)]
struct Foo {
    // Mandatory Field:
    x: i32,

    // #[builder(default)] without parameter - use the type's default
    // #[builder(setter(strip_option))] - wrap the setter argument with `Some(...)`
    #[builder(default, setter(strip_option))]
    y: Option<i32>,

    // Or you can set the default
    #[builder(default=20)]
    z: i32,
}

Build in any order:

Foo::builder().x(1).y(2).z(3).build();
Foo::builder().z(1).x(2).y(3).build();

Omit optional fields(the one marked with #[default]):

Foo::builder().x(1).build()

But you can't omit non-optional arguments - or it won't compile:

Foo::builder().build(); // missing x
Foo::builder().x(1).y(2).y(3); // y is specified twice

Features

Limitations

Conflicts

Alternatives - and why typed-builder is better

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.