如何在范围内将项目追加到地图?

时间:2018-09-07 13:48:48

标签: go

示例:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/imdario/mergo"
)

func main() {
    var DATA []map[string]interface{}
    text := []byte(`[{"id":1,"test":1},{"id":2},{"id":3,"test":3},{"test":8}]`)
    err := json.Unmarshal(text, &DATA)
    if err != nil {
        fmt.Errorf("ERR: %s", err)
    }

    var STATE map[string]interface{}
    var newState []interface{}

    fmt.Println("DATA: ", DATA)

    for _, k := range DATA {
        if err := mergo.Merge(&STATE, k, mergo.WithOverride); err != nil {
            fmt.Errorf("Error merge new and old packets: %s", err)
        }
        fmt.Println("STATE: ", STATE)

        newState = append(newState, STATE)
    }

    fmt.Println(newState)

}

我得到: [map [id:3 test:8] map [test:8 id:3] map [id:3 test:8] map [test:8 id:3]]
我想得到 [map [id:1 test:1] map [test:2 id:1] map [id:3 test:3] map [test:8 id:3]]

我不明白为什么最后一个值落入数据片中,而不是写时不明白

1 个答案:

答案 0 :(得分:0)

我意识到问题出在哪里,我需要明确复制每个值

for key,value := range STATE {
    newState[i][key] = value
}