This is a creation in Article, where the information may have evolved or changed.
Method 1: Direct Handwriting Code: (Ref.: http://golang-basic.blogspot.com/2014/07/step-by-step-guide-to-declaring-enums.html)
package mainimport "FMT"// a month specifies a month of the year (january = 1, ..). type month intconst (january month = 1 + Iotafebruarymarchaprilmayjunejulyaugustseptemberoctobernovemberdecember) 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 := decemberif 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 := 34month = month (day % 31) fmt. PRINTLN (month) val := int (month) + 4fmt. Println (Val) month = month (Val) + 1fmt. PRINTLN (Month)}
Ii. Generating code from Tools
Statement Enums.go
Package MainType Month Intconst (January month = 1 + Iotafebruarymarchaprilmayjunejulyaugustseptemberoctobernovemberdecember)
Command execution:
Go get-v-u golang.org/x/tools/cmd/stringer (download required for first use, x turn) Stringer-type=month
Automatic generation: (Ref.: Http://godoc.org/golang.org/x/tools/cmd/stringer)
Created: Month_string.go
generated by Stringer-type=month; Do not editpackage Mainimport "FMT" Const _MONTH_NAME = " Januaryfebruarymarchaprilmayjunejulyaugustseptemberoctobernovemberdecember "var _month_index = [...] uint8{0, 7, 0, A, a,,,,,,,,,,,,,, and 74}func (i Month) string () string {i-= 1if i < | | i+1 >= Mont H (Len (_month_index)) {return FMT. Sprintf ("Month (%d)", i+1)}return _month_name[_month_index[i]:_month_index[i+1]]}
Use:
Package Mainimport ("FMT") func main () {month: = januaryfmt.printf ("%d\n", month) fmt. PRINTLN (January) month = month + month (2) fmt. Printf ("%d\n", month) fmt. PRINTLN (Month)}
The feeling is a little complicated:)