更方便的在微信公众号阅读文章可以关注公众号:海生的go花园
最近在写一个需求如下,有5中金币类型,每种金币类型,有对应的金币数,以及金币领取上限。
原来的代码,是如下写法:
//金币类型
const CoinType1 = 1
const CoinType2 = 2
const CoinType3 = 3
const CoinType4 = 4
const CoinType5 = 5
//金币类型 对应的 金币数
const CoinType1CoinNum = 11
const CoinType2CoinNum = 12
const CoinType3CoinNum = 13
const CoinType4CoinNum = 14
const CoinType5CoinNum = 15
//金币类型 对应的 金币领取上限
const CoinType1LimitTimes = 101
const CoinType2LimitTimes = 102
const CoinType3LimitTimes = 103
const CoinType4LimitTimes = 104
const CoinType5LimitTimes = 105
随着金币类型的增加,每次,都要增加三个变量,且获取的时候,还要对应关系,想到用
k,v结构来优化
变量太多,不利于维护,能不加新的,最好不加
方案一:slice 来表示一一对应
//金币类型
const CoinType1 = 1
const CoinType2 = 2
const CoinType3 = 3
const CoinType4 = 4
const CoinType5 = 5
var CoinNum = []int{
CoinType1: 11,
CoinType2: 12,
CoinType3: 13,
CoinType4: 14,
CoinType5: 15,
}
var CoinLimitTimes = []int{
CoinType1: 101,
CoinType2: 102,
CoinType3: 103,
CoinType4: 104,
CoinType5: 105,
}
方案二:map 来表示一一对应
//金币类型
const CoinType1 = 1
const CoinType2 = 2
const CoinType3 = 3
const CoinType4 = 4
const CoinType5 = 5
var CoinNum = map[int]int{
CoinType1: 11,
CoinType2: 12,
CoinType3: 13,
CoinType4: 14,
CoinType5: 15,
}
var CoinLimitTimes = map[int]int{
CoinType1: 101,
CoinType2: 102,
CoinType3: 103,
CoinType4: 104,
CoinType5: 105,
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。