go 中 iota 的使用
iota 的多种用法:
-
iota只能在常量的表达式中使用。例如:fmt.Println(iota) //编译错误: undefined: iota
-
每次 const 出现时,都会让 iota 初始化为0。
const a = iota // a=0 const ( b = iota //b=0 c //c=1 相当于c=iota )
-
自定义类型,自增长常量经常包含一个自定义枚举类型,允许你依靠编译器完成自增设置。
type Stereotype int const ( TypicalNoob Stereotype = iota // 0 TypicalHipster // 1 TypicalHipster = iota TypicalUnixWizard // 2 TypicalUnixWizard = iota TypicalStartupFounder // 3 TypicalStartupFounder = iota )
iota 在下一行增长,而不是立即取得它的引用。
const ( Apple, Banana = iota + 1, iota + 2 // Apple: 1 Banana: 2 Cherimoya, Durian // = iota + 1, iota + 2 // Cherimoya: 2 Durian: 3 Elderberry, Fig //= iota + 1, iota + 2 // Elderberry: 3 Fig: 4 )
-
可跳过的值
//如果两个const的赋值语句的表达式是一样的,那么可以省略后一个赋值表达式。 type AudioOutput int const ( OutMute AudioOutput = iota // 0 OutMono // 1 OutStereo // 2 _ _ OutSurround // 5 )
中间插队
const ( i = iota j = 3.14 k = iota l ) //那么打印出来的结果是 i=0,j=3.14,k=2,l=3
-
位掩码表达式
type Allergen int const ( IgEggs Allergen = 1 << iota // 1 << 0 which is 00000001 IgChocolate // 1 << 1 which is 00000010 IgNuts // 1 << 2 which is 00000100 IgStrawberries // 1 << 3 which is 00001000 IgShellfish // 1 << 4 which is 00010000 )
本作品采用《CC 协议》,转载必须注明作者和本文链接