https://crates.io/crates/typed-builder
typed-builder = "0.5.1"
Rust Typed Builder
Creates a compile-time verified builder:
#[macro_use]
extern crate typed_builder;
#[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
浙公网安备 33010602011771号