strum icon indicating copy to clipboard operation
strum copied to clipboard

Convert between structs and enums

Open Kinrany opened this issue 1 year ago • 2 comments

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.

Kinrany avatar May 30 '23 05:05 Kinrany

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 :)

Peternator7 avatar Jul 29 '23 22:07 Peternator7

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.

Kinrany avatar Jul 31 '23 11:07 Kinrany