Go语言枚举

Go语言枚举教程

Golang 中没有 enum 关键字,要定义枚举可以使用 const 配合 iota 常量生成器 来定义。iota 不仅只生成每次增加 1 的枚举值。我们还可以利用 iota 来做一些强大的枚举常量值生成器。

Go语言枚举详解

定义

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

程序运行,结果如下:

62 golang enum.png

我们使用 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) }

程序运行,结果如下:

63 golang enum.png

我们使用 const 配合 iota 来定义枚举常量值生成器。

Go语言枚举总结

Golang 中没有 enum 关键字,要定义枚举可以使用 const 配合 iota 常量生成器来定义。