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,
    taDiv
};

In Go you can do it as:

const (
    tagBody = iota
    tagDiv
    tagHr
)

This declares 3 untyped, numeric constants. iota starts numbering of constants. tagBody has value of 0, tagDiv a value of 1 etc. This is 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