packed struct and packed union may now be used as switch prong items. They are compared solely based on their backing integer
I read this in the 0.16.0 release notes.
Which made think: if enums, packed structs and packed unions are just a ‘backing integer’ why are the comparisons >, >=, <, <= not possible for these types?
1 Like
Because they are not just their backing integer, rather they are an abstraction over bits of the backing integer.
The data has a different meaning which may not have the concepts of greater than or less than. If you need them to have those semantics you can simply cast them to the backing integer when necessary.
Equivalence on the other hand is very common to be the same, and if that is not the case then you either compare only the fields that matter or use a function.
5 Likes
I guess because Zig focuses on explicit code, since in comparing a union you might -in your head- mean to compare the active field’s value rather than it’s backing integer?
just looked at the changelog and found this but I don’t know what it means. (EDIT: I misread the title to be “Comparaison between packed unions and packed structs” maybe since I had the search bar open looking for packed struct)
@vulpesx any idea? (tagged you since you are already here)
that means exactly what it says.
Previously you couldn not use == on packed union, but you could get around that by putting them in a packed struct. Now you can just use it on packed unions directly.
The reasoning is pretty much about explicitness.
often comparing the whole of the bits with < or > just doesn’t make sense for the type.
Whereas for ==, comparing the whole of the bits makes sense more often then not.
With packed unions you are now required define all the bits, this means zig doesn’t know which bits are important for < or >. But that is fine as they often wouldn’t make sense for the type
On the other hand, since you have to define all the bits zig doesn’t have to worry about those bits you don’t use being undefined, so == is now fine.
4 Likes