Enumerated Unions (sum types)

Steven Schveighoffer schveiguy at gmail.com
Thu Sep 12 17:37:04 UTC 2024


On Thursday, 12 September 2024 at 09:44:01 UTC, Paul Backus wrote:
> On Thursday, 12 September 2024 at 03:22:07 UTC, Steven 
> Schveighoffer wrote:
>>> Access to the tag field of an enum union, if it exists, is 
>>> always @system.
>>
>> Does this mean `obj.__tag` is `@system`? Surely, having this 
>> knowledge is not a safety violation.
>
> `__tag` is an rvalue property that returns an index. Accessing 
> it is `@safe`.
>
> The tag field is a hidden field whose content is unspecified. 
> Accessing it is `@system`.
>
> They are two different things.

Given the confusion, I think it should be explicitly said that 
accessing `__tag` is `@safe`.

>
>> I think your example with the `@trusted` attribute is not 
>> safe, because the type in question may not be `@safe` to 
>> return (i.e. copy constructor not `@safe`).
>
> It returns by reference, so no copy constructor is called.

Ah, OK. I missed that.

BTW, there is an opportunity here. You can use `final switch` on 
a `__tag`, and the compiler can know when you are missing a case 
(i.e. you add another member to the enum union), and also have a 
default case assert automatically generated.

I'm also just realizing, there isn't anything to say you can't 
have more than one union member with the same type. While this is 
somewhat fine, it should be explicitly stated that this is fine 
or that it is not allowed.

For instance, std.sumtype doesn't allow this.

-Steve


More information about the dip.ideas mailing list