GO,地图按键全部更新中

问题描述 投票:0回答:1

我的做法有问题吗?我不明白为什么所有地图键都被更新,它应该只是“以太”键。

data := []byte(`
    [{".id":"*1","actual-mtu":"1500","default-name":"ether1","disabled":"false","l2mtu":"1514","type":"ether"},{".id":"*2","actual-mtu":"1500","default-name":"bridge2","disabled":"false","l2mtu":"1514","type":"bridge"}] 
`)

var dst []map[string]string
json.Unmarshal(data, &dst)

rxTx := map[string]int{"rx": 0, "tx": 0}
typeMap := map[string]map[string]int{"wlan": rxTx, "ether": rxTx, "bridge": rxTx, "wg": rxTx}

fmt.Println(typeMap)

for _, v := range dst {

    if v["type"] == "ether" {

        typeMap["ether"]["rx"] += 1

        typeMap["ether"]["tx"] += 1
    }
}

fmt.Println(typeMap)

去游乐场

输出将是

map[bridge:map[rx:1 tx:1] ether:map[rx:1 tx:1] wg:map[rx:1 tx:1] wlan:map[rx:1 tx:1]]

但我期待着

map[bridge:map[rx:0 tx:0] ether:map[rx:1 tx:1] wg:map[rx:0 tx:0] wlan:map[rx:0 tx:0]]

dictionary go multidimensional-array hashmap
1个回答
0
投票

那是因为地图实际上就像指针。 所有“wlan”、“ether”、bridge”和“wg”都指向相同的值(rxTx)。 有很多方法可以实现您想要的目标,但这里有一个快速解决方案:

data := []byte(`
    [{".id":"*1","actual-mtu":"1500","default-name":"ether1","disabled":"false","l2mtu":"1514","type":"ether"},{".id":"*2","actual-mtu":"1500","default-name":"bridge2","disabled":"false","l2mtu":"1514","type":"bridge"}] 
`)

    var dst []map[string]string
    json.Unmarshal(data, &dst)

    rxTxWlan := map[string]int{"rx": 0, "tx": 0}
    rxTxEther := map[string]int{"rx": 0, "tx": 0}
    rxTxBridge := map[string]int{"rx": 0, "tx": 0}
    rxTxWg := map[string]int{"rx": 0, "tx": 0}

    typeMap := map[string]map[string]int{"wlan": rxTxWlan, "ether": rxTxEther, "bridge": rxTxBridge, "wg": rxTxWg}

    fmt.Println(typeMap)

    for _, v := range dst {

        if v["type"] == "ether" {
            typeMap["ether"]["rx"] += 1

            typeMap["ether"]["tx"] += 1
        }
    }

    fmt.Println(typeMap)
© www.soinside.com 2019 - 2024. All rights reserved.