enum types in Go?

Well, there is none! So, let’s say one needs to implement an API with a parameter that accepts only a limited set of values. So that its invocation with invalid values can be detected at compile time. In C/C++, this could have been accomplished by defining an enum type of all valid entities and using the same enum type to declare the formal parameter. So, how to achieve this in Go? There is a pretty simple way: define a new “unexported” type and “exported” constants of this new type for all valid values. The “type” is not exported to forbid the API users from defining or adding new values and use of exported constants is thus enforced.

Here is a simple example to demonstrate this:

A good example: http://stackoverflow.com/questions/14236263/when-should-a-type-be-a-struct-containing-another-type-and-when-should-it-just

Leave a Reply

Your email address will not be published. Required fields are marked *