go 使用slice或者map 来聚合 一一对应的关系数据

2年前 (2022) 程序员胖胖胖虎阿
275 0 0

最近在写一个需求如下,有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,
}

相关文章

暂无评论

暂无评论...