Golang:iota(枚举)

120 阅读1分钟

Go并没有明确意义上的enum(枚举)定义,不过可借助iota标识符实现一组自增常量值来实现枚举类型

iota是go语言的常量计数器,只能在常量的表达式中使用,const中每新增一行常量声明iota计数一次(iota可理解为const语句块中的行索引)

const(
    x = iota //0
    y        //1
    z        //2
)

跳过某些值

const(
    x = iota //0
    _
    y        //2
    z        //3
)

自增作用范围为常量组,可在多常量定义中使用多个iota,它们各自单独计数,只许确保组中每行常量的列数量相同即可

const(
    a, b = iota, iota //0,0
    c, d              //1,1
)

如果需要中断iota自增,则需要显示恢复,且后值会与上一行常量右值表达式相同

const(
    a = iota//0
    b       //1
    c = 100//100
    d      //100
    e = iota//2
    f       // 3
)

自增默认数据类型是int,可以显示转换

const(
    a = iota  // int
    b float32 = iota  //float32
    c = iota  // int (如果不显示指定=iota,则类型和b相同)
)