英文:
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
中创建的现有地图创建了一个“别名”,因此它们指向同一个内存地址,原始地图存在于该地址上。
英文:
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论