strum
strum copied to clipboard
Convert between structs and enums
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.
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 :)
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.