rust-typed-builder icon indicating copy to clipboard operation
rust-typed-builder copied to clipboard

Improve `field_defaults` semantics

Open ifiokjr opened this issue 1 year ago • 0 comments

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.

  1. For the attributes strip_option and strip_bool there should be a way to only apply them to fields that are valid. Currently, when setting strip_option you need to use ! to negate it on non-option fields. This should not be required. Perhaps ignore_invalid as a sub attribute flag to prevent this being a breaking change.
  2. In #150, support was added for fallback methods with this syntax strip_option(fallback = custom_name_opt). This currently doesn't work for field_defaults. There should be an option available for strip_option which allows setting a fallback_prefix and fallback_suffix which 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>,
}

ifiokjr avatar Sep 14 '24 08:09 ifiokjr