Go Wiki: Iota
总结
Go 的 iota
标识符用于 const
声明,以简化递增数字的定义。由于它可用于表达式,因此提供了超越简单枚举的通用性。
每当源代码中出现保留字 const
时(即每个 const 块),iota 的值就会重置为 0,并且在每个 ConstSpec (例如,每一行)之后增加一。这可以与常量简写(省略常量名后的所有内容)结合使用,以非常简洁地定义相关常量。
Iota:https://go-lang.org.cn/ref/spec#Iota
常量声明:https://go-lang.org.cn/ref/spec#Constant_declarations
示例
官方规范中有两个很好的例子
https://go-lang.org.cn/ref/spec#Iota
这是 Effective Go 中的一个例子
type ByteSize float64
const (
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)
星期枚举示例 - iota 的计算方式 - 来自 Learn Go Programming Blog
Articles
- Go 枚举和 Iota 的终极视觉指南 2017-10-09
此内容是 Go Wiki 的一部分。