go 语言没有定义枚举类型,实现枚举的方式是通过定义一系列的自定义类型的常量来实现,go 语言中关于枚举的极简方式是 go 哲学的典型:go 语言为程序员提供他们所需要的一切,包括很多强大而方便的特性,同时又让语言尽可能的保持简小、连贯而且快速的编译和运行。
package weeks type week int //设置为不导出,避免调用者设置超出枚举范围的值 比如 week(8) const ( Sunday week = iota // if set 0 , the Following const are all 0 Monday Tuesday Wednesday Thursday Friday Saturday ) var wnMap = map[week]string{ Sunday: "Sunday", Monday: "Monday", Tuesday: "Tuesday", Wednesday: "Wednesday", Thursday: "Thursday", Friday: "Friday", Saturday: "Saturday", //must end with , } func (w week) IsRestDay() bool { return w == Saturday || w == Sunday } func (w week) String() string { if v, ok := wnMap[w]; ok { return v } //由于 week 类型设置为私有不导出,其实这个错误不会发生 return "invalid value" }
package bitflags import ( "fmt" "strings" ) type BitFlag int //const values as other languge enumeration const ( Active BitFlag = 1 << iota Send Receive ) //how to print BitFlag const value func (flag BitFlag) String() string { var flags []string //flags := []string{} //warning: Empty slice declaration via literal //suggestion: (1) var flags []string (2) flags := make([]string,0) if flag&Active == Active { flags = append(flags, "Active") } if flag&Send == Send { flags = append(flags, "Send") } if flag&Receive == Receive { flags = append(flags, "Receive") } if len(flags) > 0 { return fmt.Sprintf("%d(%s)", int(flag), strings.Join(flags, "|")) //这里如果不强制转换为int型将触发String()方法的递归调用死循环 } return "0()" }
package main import ( "bitflags" "fmt" "weeks" ) func main() { const limit = 512 //类型兼容任何数字类型 const top uint16 = 1421 // const initial can not use := const start = byte(19) // 指定与默认推断类型不一致的类型 , 默认推断19为int64 d := weeks.Monday fmt.Printf("%v is a rest day? %t.\n", d, d.IsRestDay()) fmt.Println(bitflags.Active, bitflags.Send, bitflags.Active|bitflags.Send, bitflags.Active|bitflags.Send|bitflags.Receive) }