方法1:直接手写代码:(参考:http://golang-basic.blogspot.com/2014/07/step-by-step-guide-to-declaring-enums.html)
package main import "fmt" // A Month specifies a month of the year (January = 1, ...). type Month int const ( January Month = 1 + iota February March April May June July August September October November December ) var months = [...]string{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", } // String returns the English name of the month ("January", "February", ...). func (m Month) String() string { return months[m-1] } func main() { month := December if month == December { fmt.Println("Found a December") } // %!v(PANIC=runtime error: index out of range) month = month + Month(2) // fmt.Println(month) month = January + Month(2) fmt.Println(month) month++ fmt.Println(month) day := 34 month = Month(day % 31) fmt.Println(month) val := int(month) + 4 fmt.Println(val) month = Month(val) + 1 fmt.Println(month) }
二、通过工具生成代码
声明enums.go
package main type Month int const ( January Month = 1 + iota February March April May June July August September October November December )
命令执行:
go get -v -u golang.org/x/tools/cmd/stringer (第一次使用需下载,×翻) stringer -type=Month
自动生成:(参考:http://godoc.org/golang.org/x/tools/cmd/stringer)
创建:month_string.go
// generated by stringer -type=Month; DO NOT EDIT package main import "fmt" const _Month_name = "JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember" var _Month_index = [...]uint8{0, 7, 15, 20, 25, 28, 32, 36, 42, 51, 58, 66, 74} func (i Month) String() string { i -= 1 if i < 0 || i+1 >= Month(len(_Month_index)) { return fmt.Sprintf("Month(%d)", i+1) } return _Month_name[_Month_index[i]:_Month_index[i+1]] }
使用:
package main import ( "fmt" ) func main() { month := January fmt.Printf("%d\n", month) fmt.Println(January) month = month + Month(2) fmt.Printf("%d\n", month) fmt.Println(month) }
感觉都有点小复杂 :)
有疑问加站长微信联系(非本文作者)