mmcgrana / gobyexample

Go by Example
https://gobyexample.com
7.16k stars 1.26k forks source link

Suggestion: Add an example for using iota to make enum-like constants #513

Closed JamesC01 closed 3 months ago

JamesC01 commented 6 months ago

I've learned a bit of Go recently, and one thing I struggled with is that none of the official learning resources seem to mention using iota as Go's way of doing something like C enums. When I searched "how to do enums in Go", only a few results showed, mainly from stackoverflow and random articles from websites, and some go packages implementing enums, nothing official (it is mentioned in effective go, but that doesn't seem to show on the first page of google). It rubs me the wrong way when there aren't any easy to find official sources for something like this, since it seems like it's a proper part of the language, and the intended thing you should use if you want this behaviour, so the fact that the only things that show are unofficial articles makes you question whether that is the right way, or just some sort of hack.

I think it would be very useful to add a small example to the website, maybe just after the constants example, essentially explaining that using iota inside a const block is Go's way of doing something like enums.

I'm still new to go, so I'm not sure I'm qualified to write the example myself, but hopefully someone who knows what they're doing can consider this. I think it would be quite helpful.

The example in effective go is a little complex, I think, so I think it would be nice to give a simple example showing it being used as a typical C-style enum, where the values are assigned 0, 1, 2... and then a more complex example showing the more powerful usage of iota in an expression that is assigned to the constant. Also, not sure if it's necessary, but I think it would be helpful to explicitly say that this is Go's way of doing C-like enums, just to make it clear that there isn't some other enum type.