golang iota就是用于创建递增常量的概念
基本使用就是像下面这样
const (
Red int = iota
Orange
Yellow
)
从0开始,Red为0,Orange为1,Yellow为2
如果我们想跳过某些值,可以使用_
const (
_ int =iota
Red
)
// 此时Red为1
当然如果不用_
也是会跳过的
const (
skip = "skip"
Red = iota
)
// 此时Red为1
如果要递增操作,比如bitmask,那么可以采用下列方式
const (
read = 1 << iota // 00000001
write // 00000010
)
在一些愚蠢的面试题可能会出现以下操作
const (
tomato, apple int = iota + 1, iota + 2
orange, chevy
ford, _
)
// tomato = 1, apple = 2
// orange = 2, chevy = 3
// ford = 3
- https://www.gopherguides.com/articles/how-to-use-iota-in-golang