如何使用枚举

分享到:

如何使用枚举

如何使用枚举

  1. 声明一个新的自定义类型:Weekday
1type Weekday int
  1. 为Weekday 声明相关常量
 1const (
 2 Sunday Weekday = 0
 3 Monday Weekday = 1
 4 Tuesday Weekday = 2
 5 Wednesday Weekday = 3
 6 Thursday Weekday = 4
 7 Friday Weekday = 5
 8 Saturday Weekday = 6
 9)
10fmt.Println(Sunday) // prints 0
11fmt.Println(Saturday) // prints 6
  1. 为枚举Weekday 创建共同行为
 1func (day Weekday) String() string {
 2 // declare an array of strings
 3 // ... operator counts how many
 4 // items in the array (7)
 5 names := [...]string{
 6 "Sunday", 
 7 "Monday", 
 8 "Tuesday", 
 9 "Wednesday",
10 "Thursday", 
11 "Friday", 
12 "Saturday"}
13 // → `day`: It's one of the
14 // values of Weekday constants. 
15 // If the constant is Sunday,
16 // then day is 0.
17 //
18 // prevent panicking in case of
19 // `day` is out of range of Weekday
20 if day < Sunday || day > Saturday {
21 return "Unknown"
22 }
23 // return the name of a Weekday
24 // constant from the names array 
25 // above.
26 return names[day]
27}

如何使用iota