Go中枚举的实现

前言

在 Go 中,虽然没有原生的枚举类型,但可以使用常量和自定义类型来实现枚举,并通过函数参数传递枚举值。

简单定义枚举

1
2
3
4
5
const (
Console LogType = iota
File
ConsoleAndFile
)

iota 是一个被预先声明且只能在常量声明中使用的标识符。

iota 被用作常量生成器,它会在一个 const 常量组中自动生成连续的整数值,从0开始,每次自增1。

通常情况下,iota 用于简化枚举值的定义。

比如

1
2
3
4
5
6
7
8
9
const (
A = iota // A的值为0
B // B的值为1
C // C的值为2
D = 10 // D的值为10
E // E的值为10(iota并不会重置)
F = iota // F的值为5(iota在每个const关键字出现时会重置为0)
G // G的值为6
)

定义类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
type LogType int

const (
Console LogType = iota
File
ConsoleFile
)

var logType = Console

func SetLogType(mType LogType) {
logType = mType
}

// 使用枚举类型作为函数参数
func PrintType(mType LogType) {
switch mType {
case Console:
fmt.Println("Console")
case File:
fmt.Println("File")
case ConsoleFile:
fmt.Println("Console和File")
default:
fmt.Println("无效")
}
}