Go

What does this program print? (iota)

Question 3HardGo 1.22 to 1.25
type Size int64

const (
	_       = iota             // iota = 0, skipped
	KB Size = 1 << (10 * iota) // iota = 1
	MB                         // iota = 2: repeats the expression
	GB                         // iota = 3
)

const (
	A, B = iota, iota * 10 // 0, 0
	C, D                   // 1, 10
	E    = "x"             // iota is 2, but not used
	F                      // repeats "x"
	G    = iota            // 4
)

func main() {
	fmt.Println(KB, MB, GB)
	fmt.Println(A, B, C, D, E, F, G)
}

Output:

1024 1048576 1073741824
0 0 1 10 x x 4

Why:

  • iota is the index of the ConstSpec (the line) inside a const block. It starts at 0 and resets in every new block.
  • It goes up once per line, not once per identifier, so A and B on the same line both see 0.
  • A line with no expression repeats the previous expression and its type, but uses the current iota. That is why F is "x" and MB is 1<<20.
  • Lines that don't use iota still move it forward, so G is 4.

What the interviewer wants to hear: use _ = iota to skip zero, so that the zero value can mean "unknown" or "unset". Also know how to use a typed first constant (like Size above) to build type-safe enums.

More on Language Fundamentals & Types

All 39 Language Fundamentals & Types questions