How to Use the Constant Generator iota in Golang

Created
Modified

The Constant Generator iota

Here’s an example from the time package, which defines named constants of type Weekday for the days of the week, starting with zero for Sunday. Types of this kind are often called enu- merations, or enums for short.

package main

import "fmt"

type Weekday int

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

func main() {

  fmt.Println("Sunday", Sunday)
  fmt.Println("Monday", Monday)
  fmt.Println("Saturday", Saturday)

}
$ go run main.go
Sunday 0
Monday 1
Saturday 6

The value of iota is still incremented for every entry in a constant list even if iota is not used:

package main

import "fmt"

const (
  C0 = iota + 1 // Start from one
  C1 = iota
  C2 = iota
  _
  C4 = iota // Skip value
)

func main() {

  fmt.Println(C0, C1, C2, C4) // "1 1 2 4"

}
$ go run main.go
1 1 2 4

Iota example

As a more complex example of iota, this declaration names the powers of 1024:

package main

import "fmt"

const (
  _   = 1 << (10 * iota)
  KiB // 1024
  MiB // 1048576
  GiB // 1073741824
  TiB // 1099511627776   (exceeds 1 << 32)
  PiB // 1125899906842624
  EiB // 1152921504606846976
  ZiB // 1180591620717411303424  (exceeds 1 << 64)
  YiB // 1208925819614629174706176
)

func main() {

  fmt.Printf("KiB: %d\n", KiB)
  fmt.Printf("PiB: %d\n", PiB)

}
$ go run main.go
KiB: 1024
PiB: 1125899906842624

Related Tags