在Golang中,接口类型的映射(Map)中的值是如何改变的?

huangapple go评论82阅读模式
英文:

How does value change in Golang Map of interface

问题

这是代码基础 -
https://go.dev/play/p/BeDOUZ9QhaG

输出 -

map[something:map[ACM:34.12 age:12 dune:dune]]

更改变量t中的值如何影响x?

package main

import "fmt"

func main() {
    x := make(map[string]interface{}, 10)
    x["something"] = map[string]interface{}{
        "dune": "dune", "age": 12
    }

    t := x["something"].(map[string]interface{})
    t["ACM"] = 34.12

    fmt.Println(x)
}
英文:

This is the code base -
https://go.dev/play/p/BeDOUZ9QhaG

Output -

map[something:map[ACM:34.12 age:12 dune:dune]]

How does changing values in t variable affect in x?

package main

import "fmt"

    func main() {
        x: = make(map[string] interface {}, 10)
        x["something"] = map[string] interface {} {
            "dune": "dune", "age": 12
        }
    
        t: = x["something"].(map[string] interface {})
        t["ACM"] = 34.12
       

 fmt.Println(x)
}

答案1

得分: 1

地图类型是引用类型,类似于指针或切片,所以这行代码:

t := x["something"].(map[string]interface{})
t["ACM"] = 34.12
fmt.Println(x)

只是创建了一个浅拷贝,为上面在变量x中创建的现有地图创建了一个“别名”,因此它们指向同一个内存地址,原始地图存在于该地址上。

参考链接:https://go.dev/blog/maps

英文:

> Map types are reference types, like pointers or slices,

so this line

t := x["something"].(map[string]interface{}) t["ACM"] = 34.12 fmt.Println(x) }

is just a shallow copy creating alias for the existing map you created above in x variable ,so they are pointing to same memory address where the original map you created exists.

See for reference -https://go.dev/blog/maps

huangapple
  • 本文由 发表于 2023年1月7日 13:26:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75038290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定