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

Convert between structs and enums #274

Open
Kinrany opened this issue May 30, 2023 · 2 comments
Open

Convert between structs and enums #274

Kinrany opened this issue May 30, 2023 · 2 comments

Comments

@Kinrany
Copy link

Kinrany commented May 30, 2023

Do you have any thoughts on generating structs from enums, and the reverse?

This seems like a natural thing to do because of the sum type - product type duality. So I'm imagining a couple of macros that would convert between :

struct Foo {
    bar: T,
    baz: U,
}

enum FooEnum {
    Bar(T),
    Baz(U),
}

Strum is not necessarily the right place for this, but it already does a similar conversion into enums with unit types.

@Peternator7
Copy link
Owner

Hey @Kinrany, I'm not quite sure I understand the feature + value. Generating an enum from the fields of a struct should be possible (with the caveat that you could name things in such a way that you create colliding variant names). After that, does this feature generate some method for converting between the two? I'm not exactly sure what the process would be there in either direction. Maybe a real-world example of where you'd like to use this feature would help :)

@Kinrany
Copy link
Author

Kinrany commented Jul 31, 2023

The idea is to view a Foo value as a collection of FooEnum values where each variant can only be present once.

impl IntoIterator<Item = FooEnum> for Foo is trivial; the reverse only works if we treat Option fields in Foo specially:

struct Foo {
  bar: T,
  baz: Option<U>
}

still maps to

enum FooEnum {
  Bar(T),
  Baz(U), // not Baz(Option<U>)
}

This unfortunately makes the relationship 1:M, unless all fields are made optional.

One use case is passing a set of modifiers, some or all of them optional. It makes sense to serialize them as optional fields of an object, but easier to process them as a collection.

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