I'm trying to represent a simplified chromosome, which consists of N bases, each of which can only be one of {A, C, T, G}
.
I'd like to formalize the constraints with an enum, but I'm wondering what the most idiomatic way of emulating an enum is in Go.
I am sure we have a lot of good answers here. But, I just thought of adding the way I have used enumerated types
This is by far one of the idiomatic ways we could create Enumerated types and use in Go.
Edit:
Adding another way of using constants to enumerate
As of Go 1.4, the
go generate
tool has been introduced together with thestringer
command that makes your enum easily debuggable and printable.You can make it so:
With this code compiler should check type of enum
Quoting from the language specs:Iota
So your code might be like
or
if you want bases to be a separate type from int.
Referring to the answer of jnml, you could prevent new instances of Base type by not exporting the Base type at all (i.e. write it lowercase). If needed, you may make an exportable interface that has a method that returns a base type. This interface could be used in functions from the outside that deal with Bases, i.e.
Inside the main package
a.Baser
is effectively like an enum now. Only inside the a package you may define new instances.It's true that the above examples of using
const
andiota
are the most idiomatic ways of representing primitive enums in Go. But what if you're looking for a way to create a more fully-featured enum similar to the type you'd see in another language like Java or Python?A very simple way to create an object that starts to look and feel like a string enum in Python would be:
Suppose you also wanted some utility methods, like
Colors.List()
, andColors.Parse("red")
. And your colors were more complex and needed to be a struct. Then you might do something a bit like this:At that point, sure it works, but you might not like how you have to repetitively define colors. If at this point you'd like to eliminate that, you could use tags on your struct and do some fancy reflecting to set it up, but hopefully this is enough to cover most people.