Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Go doesn't even classic type-safe integer-value enums like in C++ or enums.

Yes, you can emulate this style of enums by using iota to start a self-incrementing list of integer constants. But that's not what any language (except for C) has ever meant by "enum".

Enums are generally assumed to be type-safe and namespaced. But in Go, they are neither:

  type Color int

  const (
      Red Color = iota
      Green
      Blue
   )

   func show(color Color) {
       fmt.Printf("State: %v", color)
   }

   fun main() {
       show(Red)
       show(6)
   }
There is no namespacing, no way to — well — enumerate all the members of the enum, no way to convert the enum value to or from a string (without code-genreation tools like stringer), and the worst "feature" of all is that enums are just integers that can freely receive incorrect values.

If you want to admire a cool hack that you can show off to your friends, then yeah, iota is a pretty neat trick. But as a language feature it's just a ugly and awkward footgun. Being able to auto-increment powers of two is a very small consolation prize for all of that (and something you can easily achieve in Rust anyway with any[1] number[2] of crates[3]).

[1] https://crates.io/crates/enumflags2

[2] https://crates.io/crates/bitmask-enum

[3] https://crates.io/crates/modular-bitfield



> Go doesn't even classic type-safe integer-value enums like in C++ or enums.

Sure, but now you're getting into the topic of types. Enums produce values. Besides, Go isn't really even intended to be a statically-typed language in the first place. It was explicitly told when it was released that they wanted it to be like a dynamically-typed language, but with statically-typed performance.

If you want to have an honest conversation, what other dynamically-typed languages support type-safe "enums"?

> But that's not what any language (except for C) has ever meant by "enum".

Except all the others. Why would a enum when used when looping over an array have a completely different definition? It wouldn't, of course. Enums are called what they are in a language because they actually use enums in the implementation, as highlighted in both the Go and Rust codebases above.

Many languages couple enums with sum types to greater effect, but certainly not all. C is one, but even Typescript, arguably the most type-intensive language in common use, also went with "raw" enums like Go.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: