Explicit union tag values
#967
Replies: 4 comments
-
|
I dislike the Allowing struct-tags like could work quite well here, but you'd have to parse it - potentially every time you needed to process that field which is.... quite a big Ugh. 🤔 Could reuse the array index-assign syntax maybe? I'm not sure how much I like that, but. 🤔 |
Beta Was this translation helpful? Give feedback.
-
|
Another approach would be to use |
Beta Was this translation helpful? Give feedback.
-
|
To clarify my suggestion, the following: is not an alternative syntax. It's user-level custom tags. The compiler does not care what's in them. User-level code may use it to setup some custom serialization/deserialization engine. |
Beta Was this translation helpful? Give feedback.
-
|
Union field tags, like struct field tags, is probably the best option. I'll give it a bit of a think. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is your feature request related to a problem? Please describe.
If you want robust serialization / deserialization of
unionvalues, you need the tag values to be explicit.Suppose you have something like this:
The two variants of this union have identical memory layout. The compiler currently seems to assign tag values sequentially, starting with 1, (I assume if the
#no_nilmodifier is provided then it starts with 0).So in this case, a tag value of 1 indicates
hsl, and a tag value of 2 indicatesrgb.Suppose with this, I serialize a color instance to a binary file by just dumping its memory as a byte stream.
Later, I change the code to add a new variant, and for whatever reason, I added it to the middle:
The meanings of tag values have been changed without the explicit control of the programmer. If I do just a naive deserilization of a byte stream dumped from the previous version, it will not work. A tag value of 2 used to indicate
rgbbut now indicateshsvDescribe the solution you'd like
Just like enum values can be assigned explicitly, allow union tag values to be assigned explicitly:
Another option is to allow arbitrary string tags, similar to structs: this allows the programmer to use whatever scheme they would like for deserialization without caring the specific tag value assigned by the compiler:
Additional context
Here's a short code sample that demonstrates the memory layout of a union value:
Output:
This demonstrates that the compiler has assigned the tag value
1to indicatehsland3to indicatergb. It also demonstrates that the tag is the last byte.Beta Was this translation helpful? Give feedback.
All reactions