Go 之iota
iota是一个常量计数器,一般在常量表达式中使用,可以理解为const定义常量的行数的索引,注意是行数
使用场景
主要应用在需要枚举的地方
示例1
package main
import "fmt"
const (NoPay     = iota // 订单未支付 0Paid             // 已支付  1Cancelled        // 已取消 2PendIng          // 未发货 3Delivered        // 已发货 4Received         // 已收货 5
)func main() {fmt.Println(NoPay,Received)
}示例2
package main
import "fmt"
const (_           = iota                   // 通过分配给空白标识符忽略第一个值KB  = 1 << (10 * iota) // 1 << (10*1)MB                                   // 1 << (10*2)GB                                   // 1 << (10*3)TB                                   // 1 << (10*4)PB                                   // 1 << (10*5)EB                                   // 1 << (10*6)ZB                                   // 1 << (10*7)YB                                   // 1 << (10*8)
)
func main() {fmt.Println(KB,MB,GB)
}iota不等于0,它代表const语句块中的行索引,只有在第一行时才等于0,每出现一次常量,其所代表的数字会自动增加1
示例1:
package mainimport "fmt"const (a = iotabc = "c"de = iotaf
)func main() {fmt.Println(a, b, c, d, e, f) //0 1 c c 4 5
}示例2:
package mainimport "fmt"const (b="b"a           = iota)
func main() {fmt.Println(b,a)//b 1
}在每一个const关键字出现时被重置为0
示例:
package mainimport "fmt"const (a           = iotab
)
const (c           = iota
)func main() {fmt.Println(a,b,c)//0 1 0
}支持移位运算
package mainimport "fmt"const (a =  1 << iotabcdef
)func main() {fmt.Println(a, b, c, d, e, f) //1 2 4 8 16 32
}总结
使用iota能保证一组常量的唯一性,避免无效值,提高代码可维护性。