我有一个带有复杂键的 map
- 例如,二维数组:
m := make(map[[2][3]int]int)
当我在映射中插入一个新键时,Go 是否会对该键进行深度复制?
a := [2][3]int{{1, 2, 3}, {4, 5, 6}}
m[a] = 1
换句话说,如果我在将数组 a
用作映射键后更改它,映射是否仍然包含 a
的旧值?
最佳答案
简答,已复制。
根据规范,数组是值类型
。
Go's arrays are values. An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C). This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a pointer to the array, but then that's a pointer to an array, not an array.) https://blog.golang.org/go-slices-usage-and-internals
自己看看:
https://play.golang.org/p/fEUYWwN-pm
package main
import (
"fmt"
)
func main() {
m := make(map[[2][3]int]int)
a := [2][3]int{{1, 2, 3}, {4, 5, 6}}
fmt.Printf("Pointer to a: %p\n", &a)
m[a] = 1
for k, _ := range m {
fmt.Printf("Pointer to k: %p\n", &k)
}
}
指针不匹配。
编辑:真正的原因是当插入 map 时,键值被复制。或者,你可以继续只记住上面的规则:数组是值类型,它们的重用表示一个副本。要么在这里工作。 :)
关于dictionary - 插入 map 时,Go(深)复制键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37618408/