Skip to content

Additional generic traits for setters #131

@radekvit

Description

@radekvit

Is there a way to add additional generics bounds on field setters?

This would help in cases where setting bounds in the struct definition is annoying (which is most of the time), but the structure only makes sense with specific trait bounds.
In my use-case, I use () as the alternative to a T: SomeTrait, and only implement functionality for T: SomeTrait. The setter is only useful in cases where the T implements some additional traits.

use typed_builder::TypedBuilder;

#[derive(TypedBuilder)]
struct Generic<T: Default> {
    //                                      vvv The new syntax could be something like this
    #[builder(default, setter(strip_option, generic_bounds = Send + Sync))]
    optional_thing: Option<T>,
}

struct Defaults(*const i32);

impl Default for Defaults {
    fn default() -> Self {
        Self(&0 as *const i32)
    }
}

fn foo() {
    // ERROR: .optional_thing can only be called with T that's Default + Send + Sync
    Generic::builder().optional_thing(Defaults::default());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions