美文网首页
golang map 赋值 修改 陷阱

golang map 赋值 修改 陷阱

作者: jojo1313 | 来源:发表于2020-12-22 18:37 被阅读0次

    无法修改同一个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]]
    

    相关文章

      网友评论

          本文标题:golang map 赋值 修改 陷阱

          本文链接:https://www.haomeiwen.com/subject/kqosnktx.html