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

Add support for tuple-structs and unit-structs

Open zakarumych opened this issue 5 years ago • 3 comments

subj


This change is Reviewable

zakarumych avatar Aug 20 '18 11:08 zakarumych

  1. Please add a test
  2. Why would one even need a builder for a unit type? It doesn't offer completeness because we don't support enums, and it doesn't offer any genericness because we don't have a builder trait.

idanarye avatar Aug 20 '18 13:08 idanarye

  1. Ok.
  2. One would want builder for unit type in case this unit type is generated via macro or proc-macro. It can become complete with added enum support.

zakarumych avatar Aug 20 '18 14:08 zakarumych

I'm actually kind of worried about enum support. Enum support would mean we could do this:

#[derive(TypedBuilder)]
enum Foo {
    Bar {
        a: i32,
        b: i32,
        c: i32,
    },
    Baz {
        e: i32,
        f: i32,
        g: i32,
    },
}

assert!(Foo::build_bar().a(1).b(2).c(3).build() == Foo::Bar { a: 1, b: 2, c: 3 });
assert!(Foo::build_baz().d(4).e(5).f(6).build() == Foo::Baz { d: 4, e: 5, f: 6 });

But... I consider having complex structs as enum variants an anti-pattern, because then you need to destruct it every time you want to access any of the fields. It's better to use nested types:

#[derive(TypedBuilder)]
struct Bar {
    a: i32,
    b: i32,
    c: i32,
}

#[derive(TypedBuilder)]
struct Baz {
    e: i32,
    f: i32,
    g: i32,
}

#[derive(TypedBuilder)]
enum Foo {
    Bar(Bar),
    Baz(Baz),
}

But then you wouldn't need a builder for Foo, because you would just do:

Foo::Bar(Bar::build().a(1).b(2).c(3).build());
Foo::Baz(Baz::build().d(4).e(5).f(6).build());

Now, it would be nice if we could have Foo::build_bar() and Foo::build_baz() for that style as well - but I don't think this is possible with Rust's current type system and macro system.

idanarye avatar Aug 20 '18 20:08 idanarye