WeCodeAcademy

Go Constants and iota

Constants are fixed at compile time. iota is a counter that makes numbered constants easy, which is how Go writes enums.

ExampleGo
package main

import "fmt"

const Pi = 3.14159
const (
  Small = iota // 0
  Medium       // 1
  Large        // 2
)

type Weekday int

const (
  Sunday Weekday = iota
  Monday
  Tuesday
)

func (d Weekday) String() string {
  return [...]string{"Sun", "Mon", "Tue"}[d]
}

func main() {
  fmt.Println(Pi, Small, Medium, Large)
  fmt.Println(Monday, Tuesday)
  fmt.Printf("%d %v\n", Tuesday, Tuesday)
}
Output
3.14159 0 1 2
Mon Tue
2 Tue

Giving a type a String() method changes how fmt prints it. That is how Monday prints as Mon instead of 1.

Quick check

What does iota do inside a const block?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.