go语言type使用小技巧
- import "fmt"
- type Rank int
- const (
- Rank001 Rank = iota
- Rank002
- Rank003
- Rank004
- )
- var rewards = [...]string{
- "奖励1","奖励2","奖励3","奖励4",
- }
- func (r Rank) getReward() string {
- return rewards[r]
- }
- func main() {
- fmt.Println(Rank003.getReward())
- }
通过这样的方式,灵活的将排名与奖励对应,并且“面向对象”,将排名,这个int类型声明为排名,并为其添加成员函数。常规方式在C/C++,Java中,就直接通过2个以维数组惊醒处理,但相对而言,Go语言这种方式,真的很赞!
go time/time.go 中:
108 type Weekday int
109
110 const (
111 Sunday Weekday = iota
112 Monday
113 Tuesday
114 Wednesday
115 Thursday
116 Friday
117 Saturday
118 )
119
120 var days = [...]string{
121 "Sunday",
122 "Monday",
123 "Tuesday",
124 "Wednesday",
125 "Thursday",
126 "Friday",
127 "Saturday",
128 }
129
130 // String returns the English name of the day ("Sunday", "Monday", ...).
131 func (d Weekday) String() string { return days[d] }