zig icon indicating copy to clipboard operation
zig copied to clipboard

Proposal: permit explicit tags with `_` switch prong

Open mlugg opened this issue 2 years ago • 2 comments

Related: #12250

It is reasonable to have one switch prong which handles both any unnamed enum alternative, and some specific tags. For instance, in the compiler codebase, when switching on an InternPool.Index, we may wish to handle some fixed indices using the "normal" indexToKey logic; but we don't necessarily want to use else, since this means the compiler can't notice when we miss an alternative. What we would ideally like is to be able to write this:

switch (enum_val) {
    .special_case_1 => foo(),
    .special_case_2 => bar(),
    _, .special_case_3 => baz(),
}

The intent here is perfectly clear; the behavior it would give is generally useful for safety (as mentioned above, this allows the compiler to tell us when an alternative has not been considered, particularly when one is added); and there are no ambiguities surrounding captures, since any prong of a switch on an enum can only capture the enum value itself. Thus, I propose that the language be modified to permit this syntax.

mlugg avatar Mar 26 '24 14:03 mlugg

I don't understand what is the meaning of the _ in _, .special_case_3 => baz(), If this line means anything other than [special_case_1, special_case_2] and anything that's something (the _) or special_case_3, why not use exhaustive listing ?

switch (enum_val) {
    .special_case_1 => foo(),
    .special_case_2 => bar(),
    .special_case_3 => baz(),
}

This will too be noticed by the compiler when we add another alternative (special_case_4)

Lking03x avatar May 05 '24 09:05 Lking03x

@Lking03x this syntax relates to an existing language feature. Please see this section of the langref.

mlugg avatar May 05 '24 23:05 mlugg