Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional generic traits for setters #131

Open
radekvit opened this issue Nov 19, 2023 · 2 comments
Open

Additional generic traits for setters #131

radekvit opened this issue Nov 19, 2023 · 2 comments

Comments

@radekvit
Copy link

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());
}
@idanarye
Copy link
Owner

Why not just add the bounds on the generic when defining it?

#[derive(TypedBuilder)]
struct Generic<T: Default + Send + Sync> {

@radekvit
Copy link
Author

Because T doesn't necessarily have to have those bounds - they're only important if they're set.

Consider a bound MyCustomTrait, where T can be either T: MyCustomTrait, or ().
I'll only want to set the Option to Some when T is not (), and it needs to implement the trait.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants