Go Tutorial · Go Basics · Lesson 6 of 30

Go Constants

Declare constants with const and generate enum-like values with iota.

const

Constants are fixed at compile time:

Example 1
package main

import "fmt"

func main() {
	const Pi = 3.14159
	const Greeting = "Hello"
	const MaxUsers int = 100
	fmt.Println(Greeting, Pi*2, MaxUsers)
}

Output

Hello 6.28318 100

Run this on your computer — see “Get Started” for setup.

Untyped numeric constants have arbitrary precision and adapt to the context where they're used.

iota

Inside a const block, iota counts up from 0 — Go's way of making enums:

Example 2
package main

import "fmt"

type Status int

const (
	Pending Status = iota // 0
	Paid                  // 1
	Shipped               // 2
)

const (
	_  = iota             // skip 0
	KB = 1 << (10 * iota) // 1 << 10
	MB                    // 1 << 20
	GB                    // 1 << 30
)

func main() {
	fmt.Println(Pending, Paid, Shipped)
	fmt.Println(KB, MB, GB)
}

Output

0 1 2
1024 1048576 1073741824

Run this on your computer — see “Get Started” for setup.

Test yourself

What value does iota have on the first line of a const block?

  1. 0
  2. 1
  3. -1
  4. It depends on the type
Show answer

Answer: 0