Constants and Enumerates

Constants

Use keyword const to define constants in Go

1
2
3
4
5
6
func consts() {
const (
filename = "abc.txt"
path = "/tmp/"
)
}

Note, unlike in other languages, consts in Go is not in upper case, since upper case means public in Go.

Enumerate

Enumerate is a special type of const, e.g.

1
2
3
4
5
6
7
8
9
10
func enums() {
const (
cpp = 0
python = 1
golang = 2
javascript = 3
java = 4
)
fmt.Println(cpp, python, golang, javascript, java)
}

We could use built-in iota to simplify defining auto-incremental consts

1
2
3
4
5
6
7
8
9
10
func enums() {
const (
cpp = iota
python
golang
javascript
java
)
fmt.Println(cpp, python, golang, javascript, java)
}

It will print the results:

1
0 1 2 3 4

iota can be used in some interesting applications, e.g. enumerate bit, KB, MB etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
func enums() {

const (
b = 1 << (10 * iota) //left move by 1 digit
kb
mb
gb
tb
pb
)

fmt.Println(b, kb, mb, gb, tb, pb)
}
1
1 1024 1048576 1073741824 1099511627776 1125899906842624