为什么一个函数中的地图值受另一个函数中的映射条目影响? [英] Why is a map value in one function affected by an entry to the map in another function?

查看:143
本文介绍了为什么一个函数中的地图值受另一个函数中的映射条目影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

func test(v map[string]string) {
    v["foo"] = "bar"
}

func main() {
    v := make(map[string]string)
    test(v)
    fmt.Printf("%v\n", v) // prints map[foo:bar]
}

我是Go的新手,但据我所知,由于我将地图值传递给 test()而不是指向地图, test()函数应该修改地图的不同变量,因此不会影响 main中的变量的值()。我会期望它打印 map [] 。我测试了一个不同的场景:

I'm pretty new to Go, but as far as I was aware, since I'm passing the map value to test() and not a pointer to the map, the test() function should modify a different variable of the map, and thus, not affect the value of the variable in main(). I would have expected it to print map[]. I tested a different scenario:

type myStruct struct {
    foo int
}

func test2(v myStruct) {
    v.foo = 5
}

func main() {
    v := myStruct{1}
    test2(v)
    fmt.Printf("%v\n", v) // prints {1}
}

在这种情况下,代码的行为与我预期的一样。 main()函数中的 v 变量不受 TEST2()。那么为什么地图不同?

In this scenario, the code behaves as I would expect. The v variable in the main() function is not affected by the changes to the variable in test2(). So why is map different?

推荐答案

你是正确的,当你传递一些功能,将复制。但地图是底层数据结构的某种描述符。所以当你将地图值传递给一个函数时,只有描述符将被复制,它将表示/指向存储地图数据(条目)的相同数据结构。

You are right in that when you pass something to a function, a copy will be made. But maps are some kind of descriptors to an underlying data structure. So when you pass a map value to a function, only the descriptor will be copied which will denote / point to the same data structures where the map data (entries) are stored.

这意味着如果函数对地图条目进行任何修改(添加,删除,修改条目),这是从调用者观察到的。

This means if the function does any modification to the entries of the map (add, delete, modify entries), that is observed from the caller.

阅读 Go Blog:Go map in action 的详细信息。

请注意,同样适用于切片 channels 一般来说,您可以使用内置的 make() 功能。这就是为什么这些类型的零价值 nil ,因为这些类型的值需要一些额外的初始化,这在调用 make()时完成。

Note that the same applies to slices and channels too; generally speaking the types that you can create using the built-in make() function. That's why the zero value of these types is nil, because a value of these types need some extra initialization which is done when calling make().

在另一个例子中,你使用一个 struct 值,它们不是描述符。当您将 struct 值传递给另一个函数时,会创建一个完整的struct值复制(复制其所有字段的值)对原件没有任何影响,因为副本的内存将被修改 - 这是不同的。

In your other example you are using a struct value, they are not descriptors. When you pass a struct value to another function, that creates a complete copy of the struct value (copying values of all its fields), which –when modified inside the function– will not have any effect on the original, as the memory of the copy will be modified – which is distinct.

这篇关于为什么一个函数中的地图值受另一个函数中的映射条目影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆