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

Ensuring that at least one of a set of fields are set

Open insanitybit opened this issue 6 years ago • 5 comments

It would be great if I could say something along the lines of:

#[derive(TypedBuilder)]
struct Foo {
    #[group(a)]
    #[default]
    bar: Option<String>,
    #[group(a)]
    #[default]
    baz: Option<String>,
    #[default]
    bat: Option<String>,
}

Made up the syntax, but basically some way to signal "one or both of bar/baz must be provided".

insanitybit avatar Nov 09 '18 05:11 insanitybit

I don't think the Rust type system is flexible enough to allow this...

idanarye avatar Nov 11 '18 18:11 idanarye

Actually... I was thinking about using marker traits, which are not stable yet, but instead I can use empty fields. Just set a field for each group and override its type when any member of the group is assigned.

idanarye avatar Nov 12 '18 11:11 idanarye

I recommend stealing from #[cfg], for both optimal flexibility and familiarity.

Something like this, on the struct (not on the field any more):

#[builder(group = "a", required, any("bar", all("baz", not("quux"))))]

This would define a named group “a” (the name is for documentation, and may also be used in other places that accept a field or group, such as field dependencies which I’m about to create an issue about). In this case the group is also then declared to be required before build() can be called.

chris-morgan avatar Mar 18 '19 01:03 chris-morgan

Recently started using this crate and quickly ran into a scenario that required something like this.

Is anyone working on this? If not, is anyone able and willing to provide guidance on getting this implemented?

nCrazed avatar Apr 24 '24 18:04 nCrazed

See https://github.com/idanarye/rust-typed-builder/issues/14 and my algorithm https://codeberg.org/mo8it/sus-impls

The macro has to use the algorithm to generate implementations

mo8it avatar Apr 24 '24 20:04 mo8it