3 ms·
> Which kinda defeats the purpose doesn't it? Have you actually tried it or you just ranting that Go is not Java? Take `time.Weekday` type, for example from G
by divan 4y ago
> Which kinda defeats the purpose doesn't it?
Have you actually tried it or you just ranting that Go is not Java?
Take `time.Weekday` type, for example from Go stdlib. It's a typical use of kinda enums in Go. [1]
It serves the purpose to effectively use Weekday whenever it's needed – in literals, in tests, in debug output, etc. Internally it's just an int, but for humans it's better to work with named predefined constants. Instead of creating yet another language feature that will automagically (yes, I keep repeating it, because it matters) convert variable names into strings, Weekday type leverages other Go features to achieve it in a more appropriate way, implementing proper string conversion for long and short forms for English and leaving room for proper i18n handling (it's still a named int constant). [2] Having it as a separate named type makes it handy for proper type checking (so you can't pass some integer with incorrect value to the function expecting time.Weekday).
And now you're saying that it's all useless and wrong, because compiler is not enforcing range of values that varaible of this type can have. But I tell you that it's useful and helping code readability enormously even without being a sum type.
And I hope it's clear that when you switch to another language, the worst thing you can do is to complain that it's different from your previous favourite language. You not just switching use another syntax, but you changing the ways to do things and even philosophy. It's like moving to another country - you not just changing a language, you switching to a different culture and economy. You adopt their social norms, follow the rules of that country and pay taxes even if in your country it was all different.
So yeah, in Go there are no sum types aka enums. And you know what, Go is extremely effective at what it was designed to despite of this. And "Go enums" work just fine, until they may be improved in the future when community is in consensus on how implement it, respecting backward-compatibility rule.
[1] https://cs.opensource.google/go/go/+/refs/tags/go1.18.2:src/time/time.go;drc=90462dfc3aa99649de90bb587af56a9cb0214665;l=308 https://cs.opensource.google/go/go/+/refs/tags/go1.18.2:src/...
[2] https://cs.opensource.google/go/go/+/refs/tags/go1.18.2:src/time/format.go;drc=8a56c7742d96c8ef8e8dcecaf3d1c0e9f022f708;l=316 https://cs.opensource.google/go/go/+/refs/tags/go1.18.2:src/...