go 语言没有定义枚举类型,实现枚举的方式是通过定义一系列的自定义类型的常量来实现,go 语言中关于枚举的极简方式是 go 哲学的典型:go 语言为程序员提供他们所需要的一切,包括很多强大而方便的特性,同时又让语言尽可能的保持简小、连贯而且快速的编译和运行。
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 28 29 30 31 32 33 34 35 | 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" } |
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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()" } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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) } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步