Go iota

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

Overview

iota is referred to as an enumerator.

Go Enumerations


How Does the Compiler Assign Values to iota

The compiler parses const() sequence, and each time it encounters a <constName> <constType> = iota construct, it replaces iota with the zero-based index of the constant, as it appears in the const() sequence. Note that iota may appear by itself, or part of an expression.

In case of enumerations, the constant values that are part of the enumeration do not need to declare the iota expression anymore, it is assumed that the expression is replicated, and iota gets the subsequent values.

type Color int
type DayOfWeek int

const (
	someConstant = true      // a regular constant, it's index in the const sequence is 0
	someOtherConstant = true // another regular constant, it's index in the const sequence is 1

	red Color = iota // the first declaration of a Color constant, iota, and the constant, takes value 2, as "red" is the third constant in the sequence
	green// the second declaration of a Color constant, iota and the constant take value 3
	blue // the third declaration of a Color constant, iota and the constant take value 4
	
	yetAnotherConstant = true // another regular constant, it's index in the const sequence is 5
	
	mon DayOfWeek = iota - 6 // the first declaration of a DayOfWeek. iota takes value 6, but the iota - 6, thus the constant, take value 0
	tue	// the 'iota - 6' expression is implicitly repeated, an as 'tue' is the 7th constant, iota is 7, and iota - 6 is 1
)