Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an enum from a group of related constants in Go

Tags:

What is preferred (or right) way to group large number of related constants in the Go language? For example C# and C++ both have enum for this.

like image 298
Darius Kucinskas Avatar asked Aug 04 '11 07:08

Darius Kucinskas


2 Answers

const?

const (
    pi = 3.14
    foo = 42
    bar = "hello"
)
like image 135
newacct Avatar answered Oct 19 '22 20:10

newacct


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++.

like image 27
lnmx Avatar answered Oct 19 '22 20:10

lnmx