home

Go Beginners: Iota Enumerations

28 Jul 2013

Enum constants in Go have a super power. As opposed to C# where you only have two options for enums, either you assign each value yourself or let the compiler increment each value by one, Go has a third option.

Auto-incremented enum in C#

enum Example
{
     One = 1,
     Two,
     Three
}

Go's third option is that you can make use of repeating expressions. This works because of Go's iota enumerator. The best example can by found in the Effective Go docs.

type ByteSize float64

const (
     _           = iota // ignore first value by assigning to blank identifier
     KB ByteSize = 1 << (10 * iota)
     MB
     GB
     TB
     PB
     EB
     ZB
     YB
) 

iota is only valid when assigning constants and with each const block it starts out life with a value of zero. Each time it is used it is incremented by one.

In the example above, the first constant is _ = iota. _ is a throwaway variable in Go so we are ignoring the first value of iota (zero) and starting with a value of 1 on the next line.

KB is assigned an expression that uses iota: 1 << (10 * iota. The subsequent constants don't have any explicit value so Go repeats the last assignment. Thus, repeating expressions. Because iota increments each time, we end up with a very useful pattern generator.

Flag enumerations are a great use of this. In C# it is a manual process to assign each flag a value that increments in powers of 2.

[Flags]
enum FlagExample : int
{
     Zero = 0,
     Two = 2,
     Four = 4,
     Eight = 8
}

iota makes this much simpler in Go.

const FlagExample (
     Zero = 1 << iota
     Two
     Four
     Eight
)

Of course you don't have to use iota at all if you don't want to.

const Example (
     One = 1
     Two = 2
     Four = 4
)

Be sure and read the docs for even more info. Also, here's a playground example of what we've covered.

Go forth and code.

blog comments powered by Disqus