rust-typed-builder
rust-typed-builder copied to clipboard
Improve `field_defaults` semantics
Description
Here is the current documentation for the field_defaults(...) attribute on TypedBuilder structs.
is structured like the #[builder(...)] attribute you can put on the fields and sets default options for fields of the type. If specific field need to revert some options to the default defaults they can prepend ! to the option they need to revert, and it would ignore the field defaults for that option in that field.
I have the following proposal.
- For the attributes
strip_optionandstrip_boolthere should be a way to only apply them to fields that are valid. Currently, when settingstrip_optionyou need to use!to negate it on non-option fields. This should not be required. Perhapsignore_invalidas a sub attribute flag to prevent this being a breaking change. - In #150, support was added for fallback methods with this syntax
strip_option(fallback = custom_name_opt). This currently doesn't work forfield_defaults. There should be an option available forstrip_optionwhich allows setting afallback_prefixandfallback_suffixwhich adds the fallback to all optional methods automatically.
Possible API
use typed_builder::TypedBuilder;
#[derive(TypedBuilder)]
#[builder(field_defaults(default, setter(strip_option(ignore_invalid, fallback_suffix = "_opt")))]
struct Foo {
// Defaults to None, options-stripping is performed and a fallback
// method of `x_opt` is available.
x: Option<i32>,
// Defaults to 0, no longer need `!strip_option`:
y: i32,
// Defaults to Some(13), option-stripping is performed and a fallback
// method of `z_opt` is available:
#[builder(default = Some(13))]
z: Option<i32>,
}