Using Iota for a List of Constants (Like Enums)

Enums have been used in many programming languages in varying forms for many years. But if you’ve found this post, then you are most likely looking for how to do this in Go (golang). In Go, there’s a handy feature called iota which is a running list of ever-increasing constants. They are a consise way of presenting a list of things in a “don’t repeat yourself” way.

For example if you need to define days of the week using contants, you could:

1
2
3
4
5
6
7
8
9
const (
	Sunday DayOfWeek = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
)

Which would define Sunday as 0, and Tuesday as 2. They are useful as their value is implied by their order, but this does mean you shouldn’t re-order them after they’ve been written.

When using them, you can use them like any other constant, by their name, but be aware it won’t print the constants name, but it’s value. Here’s an example of us printing each of the values above.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import "fmt"

const (
	Sunday int = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
)

func main() {
	fmt.Println(Sunday)
	fmt.Println(Monday)
	fmt.Println(Tuesday)
	fmt.Println(Wednesday)
	fmt.Println(Thursday)
	fmt.Println(Friday)
	fmt.Println(Saturday)
}

golang iota example