go語言type使用小技巧
阿新 • • 發佈:2019-02-11
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] }