dictionary - 插入 map 时,Go(深)复制键吗?

标签 dictionary go key

我有一个带有复杂键的 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/

相关文章:

go - Blitting FBO 颜色附件

json - 如何使用 JQ 选择多个键

python - 如果字典键不可用,则返回默认值

javascript - 我如何使用 .map()、.reduce() 和 .filter() 来代替 forEach 来使我的代码简洁以免脆弱?

Python 字典函数在 Linux 上导致语法错误,但在 Windows 上不会

go - 如何将结构传递给另一个包?

docker - 如何启动 docker 容器并通过 golang 脚本运行一些命令?

python - 从具有坐标和值的字典构建 numpy 矩阵

Python 字典更新和细化循环

c++ - Linux C/C++ 键盘 ctrl+[somekey] 和 ctrl+alt+[somekey}