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

Enum of named structs boilerplate #3661

Open
rosik opened this issue Jun 20, 2024 · 2 comments
Open

Enum of named structs boilerplate #3661

rosik opened this issue Jun 20, 2024 · 2 comments

Comments

@rosik
Copy link

rosik commented Jun 20, 2024

Enum of named structs is one of usual patterns:

struct Foo {}
struct Bar {}

enum FooBar {
    Foo(Foo),
    Bar(Bar),
}

Are there any ways to reduce the amount of boilerplate if it's ever needed? I've thought of something like this:

enum FooBar {
    Foo(_),
    Bar(_),
}

I'm not sure if it's appropriate to denote it this way using InferredType.

@crlf0710
Copy link
Member

Macro-based solutions like https://docs.rs/enum_dispatch/latest/enum_dispatch/ or https://sigp.github.io/superstruct/codegen/enum.html might be useful.

On the other hand, my personal proposal in the past (this doesn't make code shorter though, but at least repeating oneself is no longer needed:

variant NewType<T>(T);

use NewType as NT;

#[derive(Clone, PartialEq)]
enum FooBar = NT<Foo> + NT<Bar>;

@pronebird
Copy link

Unless you need to pass the nested Foo or Bar in its entirety, I found it a bit more elegant to expand the enum variants to contain anonymous struct, then do destructuring when matching, binding what I need then and passing it forward.

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

3 participants