TOC

Go iota

type Weekday int

const (
    Sunday Weekday = iota // 0
    Monday                // 1
    Tuesday               // 2
    Wednesday             // 3
    Thursday              // 4
    Friday                // 5
    Saturday              // 6
)

func (day Weekday) String() string {
    names := [...]string{
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    }

    if day < Sunday || day > Saturday {
        return "Unknown"
    }

    return names[day]
}
type FileSizeUnit int

const (
    _ = iota // 忽略第一个值 0,让后续常量从 1 开始递增
    KB FileSizeUnit = 1 << (10 * iota)  // 1 << (10*1) = 1 << 10 = 1024
    MB                                  // 1 << (10*2) = 1 << 20 = 1048576
    GB                                  // 1 << (10*3) = 1 << 30 = 1073741824
    TB                                  // 1 << (10*4) = 1 << 40 = 1099511627776
)
package main

import "fmt"

func main() {
    {
        const (
            a = iota
            b
            c
        )
        fmt.Printf("%+v\n", []int{a, b, c})
        // [0 1 2]
    }
    {
        const (
            a = 1
            b = iota
            c
        )
        fmt.Printf("%+v\n", []int{a, b, c})
        // [1 1 2]
    }
    {
        const (
            a = 1
            b = 2
            c = iota
        )
        fmt.Printf("%+v\n", []int{a, b, c})
        // [1 2 2]
    }
    {
        const (
            a = 1
            b = iota
            c = iota
        )
        fmt.Printf("%+v\n", []int{a, b, c})
        // [1 1 2]
    }
}

总结

  1. 首次出现是这个常量块中变量的顺序(0 开始)
  2. 后面的常量如果没有定义,就表示是按照前面的常量定义来,只是 iota 代表的值 + 1 了
  3. 如果想跳过一个值,可以使用下划线