ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.63k stars 2.53k forks source link

Proposal: Exchange `_` for `...` in exhaustive enums #4859

Open ikskuh opened 4 years ago

ikskuh commented 4 years ago

Follow-up on a discussion with @Tetralux and others on Discord and an improvement for #2524:

The use of _ in exhaustive enums does not communicate intent precisely as it's not clear if there is "something left out", only one item, multiple items. It's not clear to a first-time reader what this symbol is telling us.

The proposal is to exchange it for the ellipsis ... which is already a token in Zig used in the switch range specification, but also is the commonly known symbol for stuff left out:

An ellipsis […] is a series of dots (typically three, such as "…") that usually indicates an intentional omission of a word, sentence, or whole section from a text without altering its original meaning.

The new syntax would be:

enum(u8) {
    a = 0,
    b = 1,
    ...
}
enum(i32) { ... }

I think this communicates much more what is expressed here than the symbol _ which tells the user that "something is ignored".

tecanec commented 4 years ago

We could change the syntax within switch-statements to something like this:

switch (x) {
    0..3 => { // Used to be "0...3"
        doThings();
    },
}

This way, we woudn't have the ... token be used for two things in a simmalar context. It also makes it simmalar to the slicing syntax. However, as pointed out by @MasterQ32 on Discord, it does mean that .. will mean inclusive in one place and exclusive in another, which may seem wierd.

Tetralux commented 4 years ago

I said this on Discord, but it bears repeating: I think ... for this is better, in no small part, because


Unlike _ =>, I think ... => in switches makes sense since it's the same syntax as what it's representing.

It also only works on non-exhaustive enums so it'd compile error if you were trying to match a range, right? - (Since ranges must always have specified bounds.) [I'm a bit tired right now, so I may be missing something rather obvious. 😁 ]

ityonemo commented 4 years ago

Just a note, for switches using underscore as a catch all match in switches is a common convention in other languages, especially those with pattern matching.

Tetralux commented 4 years ago

@ityonemo _ is not a catch-all in Zig. It's specifically for non-exhuastive enums. else => is the catch-all.

pixelherodev commented 4 years ago

Not sure it means much, but I extend my support for this!

ProkopRandacek commented 1 year ago

another option that crossed my mind is adding a keyword similar to packed:

nonexhaustive enum(u8) {
    a = 0,
    b = 1,
}

which declares the union type upfront instead of having to scan to the end. thoughts?