一个枚举(enum,enumerator 的缩写),是一组命名的常量值。枚举是一个强大 的工具,让开发者可以创建复杂的常量集,而这些常量集有着有用的名称和简单且唯一的取值。
语法示例
在一个常量声明中,iota[2] 关键字创建枚举作为连续的无类型整型常量。
type BodyPart int
const (
Head BodyPart = iota // Head = 0
Shoulder // Shoulder = 1
Knee // Knee = 2
Toe // Toe = 3
)
为什么应该使用枚举?
来看一些关于枚举你可能会有的几个疑问。首先枚举也许看起来没那么有用,但是我向你保证枚举是有用的。
constconst head = 0
HeadShoulderKneeToe
const Head = "head"const Shoulder = "shoulder"
stringint
不仅仅与空间有关系,尤其是在现代硬件十分强大。假如你有类似下面这样的一些配置变量。
const (
statusSuccess = iota
statusFailed
statusPending
statusComplete
)
statusFailedstatusCancelledfailed枚举
从 1 开始枚举
10
const (
Head = iota + 1 // 1
Shoulder // 2
Knee // 3
Toe // 4
)
带有乘法的枚举
iotaconst
const (
Head = iota + 1 // 0 + 1 = 1
Shoulder = iota + 2 // 1 + 2 = 3
Knee = iota * 10 // 2 * 10 = 20
Toe = iota * 100 // 3 * 100 = 300
)
考虑到这一点,请记住你可以做不代表你应该这样做。
跳过的值的枚举
如果你想要跳过某个值,可以使用 _ 字符,就如同忽略(函数)返回的变量一样。
const (
Head = iota // Head = 0
_
Knee // Knee = 2
Toe // Toe = 3
)
在 Go 中枚举的 String
stringString()String()
type BodyPart int
const (
Head BodyPart = iota // Head = 0
Shoulder // Shoulder = 1
Knee // Knee = 2
Toe // Toe = 3
)
func (bp BodyPart) String() string {
return [...]string{"Head", "Shoulder", "Knee", "Toe"}
// 译注:这里应该是 return [...]string{"Head", "Shoulder", "Knee", "Toe"}[bp]
}
constString()
via: https://qvault.io/golang/golang-enum/
参考资料
[1]
我最近启动了 Go Mastery,一门动手的 Golang 课程: https://qvault.io/go-mastery-course/
[2]
iota: https://golang.org/ref/spec#Iota
[3]
修改名字: https://qvault.io/clean-code/naming-variables/
[4]
常量切片: https://qvault.io/golang/golang-constant-maps-slices/
[5]
Lane Wagner: https://qvault.io/author/lane-c-wagner/
[6]
dust347: https://github.com/dust347
[7]
lxbwolf: https://github.com/lxbwolf
[8]
GCTT: https://github.com/studygolang/GCTT
[9]
Go 中文网: https://studygolang.com/