关注微信公众号《云原生CTO》更多云原生干货等你来探索
云原生技术
云原生开发
面试技巧解答
GoRustPythonIstiocontainerdCoreDNSEnvoyetcdFluentdHarborHelmJaegerKubernetesOpen Policy AgentPrometheusRookTiKVTUFVitessArgoBuildpacksCloudEventsCNIContourCortexCRI-OFalcoFluxgRPCKubeEdgeLinkerdNATSNotaryOpenTracingOperator FrameworkSPIFFESPIREThanos
在 Golang 中实现枚举
枚举可以将相关的常量归为一种类型。枚举是一个强大的功能,用途广泛。然而,在 Go 中,它们的实现方式与大多数其他编程语言大不相同。
Go
Golangiota
什么是iota?
iotaconstantiota
iota012const0const
package main
import "fmt"
const (
c0 = iota
c1 = iota
c2 = iota
)
func main() {
fmt.Println(c0, c1, c2) //Print : 0 1 2
}
iota= iota
package main
import "fmt"
const (
c0 = iota
c1
c2
)
func main() {
fmt.Println(c0, c1, c2) //Print : 0 1 2
}
10iota
package main
import "fmt"
const (
c0 = iota + 1
c1
c2
)
func main() {
fmt.Println(c0, c1, c2) // Print : 1 2 3
}
您可以使用空白标识符跳过常量列表中的值。
package main
import "fmt"
const (
c1 = iota + 1
_
c3
c4
)
func main() {
fmt.Println(c1, c3, c4) // Print : 1 3 4
}
使用 iota 实现枚举
为了实现我们必须执行的自定义枚举类型考虑以下
- 声明一个新的自定义类型——整数类型。
- 声明相关常量——使用iota.
- 创建通用行为——给类型一个String函数。
- 创建额外的行为——给类型一个EnumIndex函数。
示例 1:为工作日创建一个枚举。
package main
import "fmt"
// Weekday - Custom type to hold value for weekday ranging from 1-7
type Weekday int
// Declare related constants for each weekday starting with index 1
const (
Sunday Weekday = iota + 1 // EnumIndex = 1
Monday // EnumIndex = 2
Tuesday // EnumIndex = 3
Wednesday // EnumIndex = 4
Thursday // EnumIndex = 5
Friday // EnumIndex = 6
Saturday // EnumIndex = 7
)
// String - Creating common behavior - give the type a String function
func (w Weekday) String() string {
return [...]string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}[w-1]
}
// EnumIndex - Creating common behavior - give the type a EnumIndex function
func (w Weekday) EnumIndex() int {
return int(w)
}
func main() {
var weekday = Sunday
fmt.Println(weekday) // Print : Sunday
fmt.Println(weekday.String()) // Print : Sunday
fmt.Println(weekday.EnumIndex()) // Print : 1
}
示例 2:为方向创建一个枚举。
package main
import "fmt"
// Direction - Custom type to hold value for week day ranging from 1-4
type Direction int
// Declare related constants for each direction starting with index 1
const (
North Direction = iota + 1 // EnumIndex = 1
East // EnumIndex = 2
South // EnumIndex = 3
West // EnumIndex = 4
)
// String - Creating common behavior - give the type a String function
func (d Direction) String() string {
return [...]string{"North", "East", "South", "West"}[d-1]
}
// EnumIndex - Creating common behavior - give the type a EnumIndex functio
func (d Direction) EnumIndex() int {
return int(d)
}
func main() {
var d Direction = West
fmt.Println(d) // Print : West
fmt.Println(d.String()) // Print : West
fmt.Println(d.EnumIndex()) // Print : 4
}
结论
GolangGolangiotaandconstants