Allow explicit null
packing optimization in non-exhaustive and sized enums
#12524
Labels
optimization
proposal
This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone
Hello, it would be great if we would allow explicitly setting a value for
null
on an enum to allow for setting the value of it when the enum isnull
. The optimization is similar to the nullable pointer optimization which allowsnull
to be coerced to null pointers as0
. The following syntax can be used and is non-breaking as parsing fails on the current version of Zig:The
null
variant must have an explicit initializer so as to not confuse it with a regular variant. I am not sure, but it may also be a good idea to limit this variant to non-exhaustive sized enums because the optimization could technically be possible by default on regular enums as the ABI is unspecified.When you specify a
null
variant, it is impossible to construct thenull
via that enum itself (e.g. through alias):The
null
variant only has meaning for an optional type which contains the enum. In which case, the option part is packed and any timenull
is assigned to the optional type it will be set to the value of the null variant. This allows for far more beautiful DX when using the optional enum type.A use-case I have for this currently is for packing the optional values of garbage-collected references which are secretly indices using a null tag to stay in
u32
even when it's optional. I have been just explicitly naming the tag but this means I cannot use the other amazing syntatic features of optional types such as nullable if expressions andorelse
.The text was updated successfully, but these errors were encountered: