Go中使用iota

iota是Go语言的一个关键字,它被用作常量计数器。使用iota能简化定义,在定义枚举时很有用。以下列举了iota的一些关键用法:

  • iota只能在常量表达式中使用。
fmt.Println(iota) // 编译错误:undefined: iota
  • iota默认值为0,并逐步增1。
const (
    cpp = iota // 0
    java       // 1 java=iota
    python     // 2 python=iota
    golang     // 3 golang=iota
)
  • 每次const出现时,iota将被重置为0。
const a = iota // a=0
const (
    b = iota   // b=iota b=0
    c          // c=iota c=1
)
  • 跳过某些值。
const (
    cpp = iota // 0
    _          //
    python     // 2
    golang     // 3
    javascript // 4
)
  • 自增长常量包含一个自定义枚举类型,允许我们依靠编译器完成自增设置。
type mytype int

const (
    ver0 mytype = iota // 0
    ver1               // 1 ver1 mytype = iota
    ver2               // 2 ver2 mytype = iota
    ver3               // 3 ver3 mytype = iota
)
  • 位掩码表达式。
type mytype int

const (
    a mytype = 1 << iota // 1 << 0 which is 00000001
    b                    // 1 << 1 which is 00000010
    c                    // 1 << 2 which is 00000100
    d                    // 1 << 3 which is 00001000
    e                    // 1 << 4 which is 00010000
)
  • iota可参与运算的另一个例子。
const (
    b = 1 << (10*iota) // 1 << (10*0)
    kb                 // 1 << (10*1)
    mb                 // 1 << (10*2)
    gb                 // 1 << (10*3)
    tb                 // 1 << (10*4)
    pb                 // 1 << (10*5)
)
  • 定义在一行的情况,iota在下一行增长(在同一行,iota相同),而不是立即取得它的引用。
const (
    Apple, Banana = iota + 1, iota + 2 // 1, 2
    Pear, Grape                        // 2, 3 iota+1, iota+2
    Orange, Watermelon                 // 3, 4 iota+1, iota+2
)
  • 中间插队,虽然只使用了两次iota,但每次新起一行iota都会计数。
const (
    i = iota // 0
    j = 3.14 // 3.14
    k = iota // 2
    l        // 3
)