golang-5.png

枚举类型

func enums(){
    const(
        left = 0
        top = 1
        right = 2
        bottom = 3
    )
    fmt.Println(left,top,right,bottom)
}

在 go 语言中没特别地为枚举指定创建方法,可以通过定 func ,然后在其中创建静态变量来定义枚举。

const(
        left = iota
        top
        right
        bottom
    )

在 go 语言中可以使用 iota 来创建枚举,iota 为自增值,所以输出为

0 1 2 3

可以使用 _ 进行跳值,例如这里枚举用于俄罗斯方块,没有上我们就可以将 top 跳掉

const(
    left = iota
    _
    right
    bottom
)
// b, kb, mb, gb, tb, pb
    const (
        b = 1 << (10 * iota)
        kb
        mb
        gb
        tb
        pb
    )

    fmt.Println(b,kb,mb,gb,tb,pb)
    // 1 1024 1048576 1073741824 1099511627776 1125899906842624
Golang1.png