what iota in Go

tags: learning go programming

content

  • Go source code:
const iota = 0 // Untyped int.
  • iota is a keyword in Go to define automatically increasing constants
const (
	Zero = iota
	One
)
  • in this case, Zero is integer 0, One is 1

  • skip a number

const (
	Zero = iota
	_ 
	Two
)
  • start from 1
const (
	One = iota + 1
	Two
)
  • it doesn’t have to be int
const (
	Zero float32 = iota
	One
)
fmt.Printf("%v, %T\n", Zero, Zero)  // prints `0, float32`
fmt.Printf("%v, %T\n", One, One)    // prints `1, float32`
  • the types can be mixed too
type MyInt int
const (
	Zero = iota
	One float32 = iota
	Two
	Three float64 = iota
	Four MyInt = iota
)
  • but not string, only number types
type MyString string
const (
	Zero bool = iota  // compilation error
	One MyString = iota  // compilation error
)

up

down

reference