乐趣区

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

最近在写一个需要如下,有 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,
}
退出移动版