golang map 赋值 修改 陷阱

2020-12-22  本文已影响0人  jojo1313

无法修改同一个make创建的map,只能修改不同make创建的map

func Maptest() {
    var data_list []map[string]interface{}
    subdata := make(map[string]interface{}) //第一次make
    subdata["synctag"] = ""
    data_list=append(data_list,subdata)
    subdata = make(map[string]interface{}) //第二次make
    subdata["synctag"] = "1"
    data_list=append(data_list,subdata)
    fmt.Println("==========")
    fmt.Println(data_list)
    data_list[0]["synctag"]="10.21.11.13"
    fmt.Println(data_list)

}
返回结果: 修改成功
==========
[map[synctag:] map[synctag:1]]
[map[synctag:10.21.11.13] map[synctag:1]]
func Maptest() {
    var data_list []map[string]interface{}
    subdata := make(map[string]interface{}) //make一次
    subdata["synctag"] = ""
    data_list=append(data_list,subdata)
    //subdata = make(map[string]interface{})
    subdata["synctag"] = "1"
    data_list=append(data_list,subdata)
    fmt.Println("==========")
    fmt.Println(data_list)
    data_list[0]["synctag"]="10.21.11.13"
    fmt.Println(data_list)

}
返回结果:修改失败
==========
[map[synctag:1] map[synctag:1]]
[map[synctag:10.21.11.13] map[synctag:10.21.11.13]]
上一篇下一篇

猜你喜欢

热点阅读