First Draft: Nominal Sum Types via `enum union` and `switch` Expressions

Juraj junk at vec4.xyz
Thu Sep 17 06:58:10 UTC 2026


On Tuesday, 15 September 2026 at 22:25:13 UTC, Meta wrote:

> This isn't a knock against std.sumtype; it's an incredibly 
> well-designed implementation. But no matter how good the 
> implementation is, it'll never be able to look inside a 
> delegate or template lambda passed to `match`, to show the user 
> where exactly it's failing; and it'll never be able to offer 
> error messages as good as those a language-level solution can. 
> Not without AST macros, at least.


You actually can, `static assert` is still a little bit too 
spamy, but so is compiler.

```d
enum HAS_SAME_RT = () {
     alias RT_0 = ReturnType!(HANDLERS[0]);
     foreach (H; HANDLERS[1 .. $]) if (!is(RT_0 == ReturnType!H)) 
return false;
      return true;
} ();

static assert (HAS_SAME_RT, "Return type missmatch");
```

> The compiler can lower a switch expression into a jump table, 
> instead of the nested lambda calls of the current library 
> solutions. Even if they're aggressively inlined, there's very 
> little chance they'll get optimized as well as a language 
> construct can be.

If performance is desired, you can always go with something like:
```d
TaggedUnion!(int, string, bool) x = false;

with (x) switch (kind) {
     case ToKind!int: {
         // ...
         break;
     }

     case ToKind!string: {
         // ...
         break;
     }

     default : break;
}
```




More information about the dip.development mailing list