iota使用方法和原理
简述一下iota?
iota是golang的一个关键字,是一个常量计数器,用于枚举的场景,只能出现在const常量声明中,每次换行自增1,每次遇到const声明重置为0
iota的写法是什么?
// 多个常量
const (
a = iota // 0
_
b // 2
c // 3
)
// 单个常量
const a = iota
iota的源码看过吗?什么原理?
// 只有一行代码,位于go/src/builtin/builtin.go中
// iota is a predeclared identifier representing the untyped integer ordinal
// number of the current const specification in a (usually parenthesized)
// const declaration. It is zero-indexed.
const iota = 0 // Untyped int.
是一个事先声明好的常量0,在编译的时候就会被替换成相应的常量,具体处理iota的源码在Go 工具源码库中。
如果iota在一个const声明里多次出现,或没有出现在第一行,或一行中出现了多次,iota的值是多少?
在同一个const代码块中,只要使用了iota,就是从第一行开始计数0,然后逐行递增,同一行的两个iota值也是相等的。但是空行不会递增,除非用下划线“_”占位,也算是一行。