Create an enum from a group of related constants in Go

It depends on what do you want to achieve by this grouping. Go allows grouping with the following braces syntax:

const (
    c0 = 123
    c1 = 67.23
    c2 = "string"
)

Which just adds nice visual block for a programmer (editors allow to fold it), but does nothing for a compiler (you can not specify a name for a block).

The only thing that depends on this block is the iota constant declaration in Go (which is pretty handy for enums). It allows you to create auto increments easily (way more than just auto increments: more on this in the link).

For example this:

const (
    c0 = 3 + 5 * iota
    c1
    c2
)

will create constants c0 = 3 (3 + 5 * 0), c1 = 8 (3 + 5 * 1) and c2 = 13 (3 + 5 * 2).


My closest approach to enums is to declare constants as a type. At least you have some type-safety which is the major perk of an enum type.

type PoiType string

const (
    Camping            PoiType = "Camping"
    Eatery             PoiType = "Eatery"
    Viewpoint          PoiType = "Viewpoint"
)

There are two options, depending on how the constants will be used.

The first is to create a new type based on int, and declare your constants using this new type, e.g.:

type MyFlag int

const (
    Foo MyFlag = 1
    Bar
)

Foo and Bar will have type MyFlag. If you want to extract the int value back from a MyFlag, you need a type coersion:

var i int = int( Bar )

If this is inconvenient, use newacct's suggestion of a bare const block:

const (
    Foo = 1
    Bar = 2
)

Foo and Bar are perfect constants that can be assigned to int, float, etc.

This is covered in Effective Go in the Constants section. See also the discussion of the iota keyword for auto-assignment of values like C/C++.


const?

const (
    pi = 3.14
    foo = 42
    bar = "hello"
)

Tags:

Enums

Go