Use of iota keyword

Go basics: use of iota keyword

Introduction to iota

iota is a constant counter in the Go language and can only be used in constant expressions.

Its value starts from 0. Each new row in const will cause iota to count once, that is, iota will increase by 1 (from this point of view, iota can be regarded as the row index in the const block, recording the number of rows), and its value has always been It increases by 1 until the next const keyword is encountered, and its value is reset to 0.

In a constant declaration, if a constant is not assigned a value, it has the same value as the previous line.

Using iota can simplify definitions and is useful when defining enumerations.

Use of iota

iota can only be used in constant expressions

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

Every time const appears, iota is initialized to 0

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

Custom type

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

Skippable values

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

bitmask expression

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
)

Define order of magnitude

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)
)

When defined on one line, iota is incremented on the next line instead of getting its reference immediately.

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

Cutting in the queue

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

Guess you like

Origin blog.csdn.net/weixin_37909391/article/details/130852416