iota关键字的使用

Go基础:iota关键字的使用

iota介绍

iota是go语言的常量计数器,只能在常量的表达式中使用。

其值从0开始,在const中每新增一行将使得iota计数一次,即iota自己增长1(从这点来看,iota可以看成const块中的行索引,记录行数),其值一直自增1直到遇到下一个const关键字,其值才被重新置为0.

在常量声明中,如果一个常量没有赋值,则他就跟上一行的赋值相同。

使用iota能简化定义,在定义枚举时很有用。

iota的使用

iota只能在常量的表达式中使用

// 编译错误: undefined: iota
fmt.Println(iota)

每次 const 出现时,都会让 iota 初始化为0

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

自定义类型

type Stereotype int
const (
    TypicalNoob Stereotype = iota // 0
    TypicalHipster                // 1
    TypicalUnixWizard             // 2
    TypicalStartupFounder         // 3
)

可跳过的值

type AudioOutput int
const (
    OutMute AudioOutput = iota // 0
    OutMono                    // 1
    OutStereo                  // 2
    _
    _
    OutSurround                // 5
)

位掩码表达式

type Allergen int
const (
    IgEggs Allergen = 1 << iota // 1 << 0 which is 00000001 = 1
    IgChocolate                 // 1 << 1 which is 00000010 = 2
    IgNuts                      // 1 << 2 which is 00000100 = 4
    IgStrawberries              // 1 << 3 which is 00001000 = 8
    IgShellfish                 // 1 << 4 which is 00010000 = 16
)

定义数量级

type ByteSize float64
const (
    _           = iota   // ignore first value by assigning to blank identifier
    KB ByteSize = 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)
)

定义在一行的情况,iota 在下一行增长,而不是立即取得它的引用

const (
    Apple, Banana = iota + 1, iota + 2  // Apple = 1, Banana = 2
    Cherimoya, Durian   // Cherimoya = 2, Durian = 3
    Elderberry, Fig     // Elderberry = 3, Fig = 4
)

中间插队

const (
    i = iota    // 0
    j = 3.14    // 3.14
    k = iota    // 2
    l   // 3
)

猜你喜欢

转载自blog.csdn.net/weixin_37909391/article/details/130852416