1、golang中iota是什么
iota是常量的计数器,可以理解为const定义常量的行数的索引,注意是行数。
2、应用场景
主要应用场景是在需要枚举的地方
3、易错点
因为iota一般出现在const语句块的第一行,不少的初学者会将之认为iota就是0,这是不对的。
准确的说:iota出现在const语句块中的第几行,那么它就是几,当然这里的行数的索引也是以0为开始
4、例子
package main
import "fmt"
const (
a = iota // 0
b // 1
c // 2
)
const (
x = 1 // 1
y = iota // 1
z // 2
)
// 为什么c1不是2?
// 因为b1为100,所以按照golang常量定义的简便写法,c1为100
const (
a1 = iota
b1 = 100
c1
d1 = iota
e1
)
func main() {
fmt.Println(a, b, c) // 0 1 2
fmt.Println(x, y, z) // 1 1 2
fmt.Println(a1, b1, c1, d1, e1) // 0 100 100 3 4
}
原文:https://www.cnblogs.com/chenbaoding/p/12197244.html