iota
It is a constant counter in go language and can only be used in constant expressions.
iota
Will be reset to 0 when the const keyword is present. Each new line of constant declaration in const will iota
count once (iota can be understood as the line index in the const statement block). Using iota simplifies the definition and is useful when defining enumerations.
for example:
const (
n1 = iota //0
n2 //1
n3 //2
n4 //3
)
A few common iota
examples:
Use _
skip certain values
const (
n1 = iota //0
n2 //1
_
n4 //3
)
iota
Statement cut in the middle
const (
n1 = iota //0
n2 = 100 //100
n3 = iota //2
n4 //3
)
const n5 = iota //0
Define the order of magnitude (the <<
left shift operation here means 1<<10
that the binary representation of 1 is shifted to the left by 10 bits, that is, it 1
becomes 10000000000
1024 in decimal. Similarly, 2<<2
it means that the binary representation of 2 is shifted to the left by 2 bits, also It is 10
changed from to 1000
, which is 8 in decimal.)
const (
_ = iota
KB = 1 << (10 * iota)
MB = 1 << (10 * iota)
GB = 1 << (10 * iota)
TB = 1 << (10 * iota)
PB = 1 << (10 * iota)
)
Multiple iota
definitions on one line
const (
a, b = iota + 1, iota + 2 //1,2
c, d //2,3
e, f //3,4
)