Emulating enums

suggest change

Go 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
)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents