Golang 中没有 enum 关键字,要定义枚举可以使用 const 配合 iota 常量生成器 来定义。iota 不仅只生成每次增加 1 的枚举值。我们还可以利用 iota 来做一些强大的枚举常量值生成器。
const(
identifier1 type = iota
identifier2
identifier3
...
)
使用 iota 关键字定义常量,其中 identifier1 对应的值为 0。
使用 iota 关键字定义枚举
package main
import (
"fmt"
)
type Error int
func main() {
fmt.Println("Hello 嗨客网(www.haicoder.net)")
//Golang 使用 const 配合 iota 来模拟枚举
const (
Ok Error = iota
ErrParam
ErrNetwork
ErrDatabase
)
fmt.Println(Ok, ErrParam, ErrNetwork, ErrDatabase)
}
程序运行,结果如下:
我们使用 const 配合 iota 来定义枚举。
使用 iota 定义枚举常量值生成器
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello 嗨客网(www.haicoder.net)")
//Golang 使用 const 配合 iota 来模拟枚举
const (
B = 1 << (10 * iota)
KB
MB
GB
TB
PB
)
fmt.Println(B, KB, MB, GB, TB, PB)
}
程序运行,结果如下:
我们使用 const 配合 iota 来定义枚举常量值生成器。
Golang 中没有 enum 关键字,要定义枚举可以使用 const 配合 iota 常量生成器来定义。