GO,Map键正在全部更新

tktrz96b  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(97)

我做的有什么不对吗?我不明白为什么所有的Map键都被更新了,应该只有“以太”键。

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)

Go Playground
输出为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]]

yx2lnoni

yx2lnoni1#

这是因为Map实际上就像指针,所有的“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)

相关问题