Hacker News new | ask | show | jobs
by beautron 842 days ago
I love Go's lightweight, somewhat implicit style of doing enums.

You just declare an int type, and then a list of constants of that type.

People are complaining about 'iota' here, but I think it's slick and great. It combines so nicely with eliding types and values from subsequent const declarations:

  type MyEnum int

  const (
      Value1 MyEnum = iota
      Value2
      Value3
      ...
  )
Nice and simple. Most of the syntax is just the enum value identifiers. And it works well for bit flags too:

  type MyFlags int

  const (
      Flag1 MyFlags = 1 << iota
      Flag2
      Flag3
      ...
  )
Most of the above syntax isn't specific to enums (so you're already getting a lot of other things from it). The only enum-specific syntax is iota and the eliding type/value rule.

People seem to want their languages to have all sorts of guardrails, but I find many of these cumbersome. Go gives me the one enum guardrail I care about: The enums are different types, so I can't use a MyEnum as a MyFlag, or vice versa.

I've worked on giant Go codebases, with Go-style enums all over the place, and the lack of compiler-enforced exhaustive enum switches just hasn't been a problem. And it's nice to be able to use non-exhaustive switches, when you want them. Go is simple and flexible here.

The article criticizes Go incorrectly with statements such as these:

> This also means any function that uses these or a struct that contains these can also just take an int value.

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

This is just not true. Here's an example you can run: https://go.dev/play/p/8VGufuxgK6b

The above example tries to assign an int variable to a MyEnum variable, and gives the following error: "cannot use myInt (variable of type int) as MyEnum value in variable declaration"

This error directly contradicts what is claimed in the article. Perhaps they mean that MyEnum will accept an integer literal, in which case I would argue that a guardrail here is silly, because again the problem just doesn't really come up in practice. Regardless, the author is not being very precise or clear in their thinking.