Hacker News new | ask | show | jobs
by divan 844 days ago
It's actually the coolest thing about Go enums, that they just it – enums.

Developers with a background in other languages assume all enums' use cases need string representation. Well, no. They are needed sometimes, but not always.

The same with the ability to pass int to the enum. Author says:

> Anywhere that accepts an Operation Enum type will just as happily accept an int.

Well, this is simply not true. [1] You'll have to cast your int into your enum, which is totally fine if it's your intent. Granted, there are plenty of valid cases where you need validated input, especially for the public libraries. But hey, not every code is a publicly facing library, and not all need this validation. Why spend CPU and memory on something that probably won't be needed, and that can be implemented with the existing language primitives?

In the end, the author did a great job of solving his own requirements around enums and even wrote a code generator that helps him generate this for millions of enum types per second. :)

[1] https://play.golang.com/p/Ch-IZ26p0v8

1 comments

>> Anywhere that accepts an Operation Enum type will just as happily accept an int.

>Well, this is simply not true.

As comment above [1] pointed out `printOperation(2)` is still valid.

[1] https://news.ycombinator.com/item?id=39565640

Not trying to nitpick here, but '2' is not an int here. It's the constant evaluated at compile time. But yeah, valid case if users of your code are in the habit of typing magic numbers into your function that expects enum.

My understanding is that on a practical level, these kinds of issues arise from misusing types (or not caring about them) and naively putting variables of one type into the function that expects another. Examples with number constants typed in manually do not hold ground.