Emulating enums
suggest changeGo doesn’t have a syntax for enumerations, but you can emulate it with constants and a naming scheme.
Consider a C++ enum:
enum {
tagHtml,
tagBody,
tagDiv
};
In Go you can do it as:
const (
tagBody = iota
tagDiv
tagHr
)
This declares three untyped numeric constants. iota numbers them from zero in declaration order: tagBody is 0, tagDiv is 1, and so on. That is a convenient way to assign unique numeric values.
If the values matter, you can assign them explicitly:
const (
one = 1
five = 5
seven = 7
)
Adding type safety
In the above example tagBody etc. is an untyped constant so it can be assigned to any numeric type.
We can define a unique type for our enum:
type HTMLTag int
const (
tagBody HTMLTag = iota
tagDiv
tagHr
)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents