Crates.io | typed-builder |
lib.rs | typed-builder |
version | 0.20.0 |
source | src |
created_at | 2017-10-04 23:49:38.955558 |
updated_at | 2024-08-22 17:16:35.789638 |
description | Compile-time type-checked builder derive |
homepage | |
repository | https://github.com/idanarye/rust-typed-builder |
max_upload_size | |
id | 34443 |
size | 84,272 |
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
#[builder(setter(into))]
to make their setters accept Into
values..build()
.#[builder(default)]
to make them optional and specify a default value when the user does not set them..builder()
method..build()
method.TypedBuilder
accepts arbitrary Rust code for #[builder(default = ...)]
, but other custom derive proc-macro crates may try to parse them using the older restrictions that allow only literals. To solve this, use #[builder(default_code = "...")]
instead.Result
you need to unwrap.Licensed under either of
at your option.
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.