golang枚举类型
go语言并没有提供enum的定义,我们可以使用const来模拟枚举类型。
type PolicyType int32 const ( Policy_MIN PolicyType = 0 Policy_MAX PolicyType = 1 Policy_MID PolicyType = 2 Policy_AVG PolicyType = 3 )
这里定义了一个新的类型PolicyType,并且定义了4个常量(Policy_MIN, Policy_MAX, Policy_MID, Policy_AVG),类型是PolicyType。
使用举例
func foo(p PolicyType) { fmt.Printf("enum value: %v\n", p) } func main() { foo(Policy_MAX) }
运行结果
$ go build && ./main enum value: 1
我们看到输出值是1,就是枚举常量Policy_MAX的值,我们还可以给enum添加输出函数,把枚举数字常量变换成字符串。
func (p PolicyType) String() string { switch (p) { case Policy_MIN: return "MIN" case Policy_MAX: return "MAX" case Policy_MID: return "MID" case Policy_AVG: return "AVG" default: return "UNKNOWN" } }
综合起来完成的使用例子如下:
package main import ( "fmt" ) type PolicyType int32 const ( Policy_MIN PolicyType = 0 Policy_MAX PolicyType = 1 Policy_MID PolicyType = 2 Policy_AVG PolicyType = 3 ) func (p PolicyType) String() string { switch (p) { case Policy_MIN: return "MIN" case Policy_MAX: return "MAX" case Policy_MID: return "MID" case Policy_AVG: return "AVG" default: return "UNKNOWN" } } func foo(p PolicyType) { fmt.Printf("enum value: %v\n", p) } func main() { foo(Policy_MAX) }
运行结果
$ go build && ./main enum value: MAX
模拟枚举类型
type Enum interface { name() string ordinal() int values() *[]string } type GenderType uint const ( MALE = iota FEMALE ) var genderTypeStrings = []string{ "MALE", "FEMALE", } func (gt GenderType) name() string { return genderTypeStrings[gt] } func (gt GenderType) ordinal() int { return int(gt) } func (gt GenderType) values() *[]string { return &genderTypeStrings } func main() { var ds GenderType = MALE fmt.Printf("The Gender