使用说明
iota常用于const表达式中,其值是从零开始,const声明块中每增加一行iota值自增1
原理
const块中每一行在GO中使用spec数据结构描述
// A ValueSpec node represents a constant or variable declaration
// (ConstSpec or VarSpec production).
ValueSpec struct {
Doc *CommentGroup // associated documentation; or nil
Names []*Ident // value names (len(Names) > 0) const一行定义中的变量名切片
Type Expr // value type; or nil
Values []Expr // initial values; or nil
Comment *CommentGroup // line comments; or nil
}
const块实际上是spec类型的切片,用于表示const中的多行
iota实际上就是这个切片的下标索引值,随着const行的增加而增加
for iota, spec := range ValueSpecs {
for i, name := range spec.Names {
obj := NewConst(name, iota...) //此处将iota传入,用于构造常量
...
}
}
注意:const声明还有个特点,即第一个常量必须指定一个表达式,后续的常量如果没有表达式,则继承上面的表达式。
const (
a = 1 //表达式 = 1
b //继承表达式
)
func main() {
fmt.Println(a) // 1
fmt.Println(b) // 1
}
const (
// <<左移运算(优先级高于 ’-‘号)
bit0, mask0 = 1 << iota, 1<<iota - 1 //const声明第0行,即iota==0
bit1, mask1 //const声明第1行,即iota==1, 表达式继承上面的语句
_, _ //const声明第2行,即iota==2
bit3, mask3 //const声明第3行,即iota==3
)
func main() {
fmt.Printf("bit0 %v, mask0 %v \n", bit0, mask0) //bit0 1, mask0 0
fmt.Printf("bit1 %v, mask1 %v \n", bit1, mask1) //bit1 2, mask1 1
fmt.Printf("bit3 %v, mask3 %v \n", bit3, mask3) //bit3 8, mask3 7
}