我正在尝试创建“关联” map 。问题是 superMap 收集了 aMap 的所有值。
基本上,即使我想在每次查看时只存储一个 amap 实例,我最终也会存储当前实例加上所有先前的循环。 supermap[value] = amap[value]
。然而,下面的代码片段存储了 supermap[value] = amap
。原因是我找不到任何方法来解决这个问题。如果我在每次循环后删除 aMap 的旧值,它们也会从 supermap
中删除。
package main
import (
"fmt"
)
func main() {
aData := map[int]string{
0: "apple",
1: "samsung",
2: "htc",
3: "sony",
}
dir := []string{"user", "doc", "bin", "src"}
aMap := make(map[int]string)
superMap := make(map[string]map[int]string)
for k, v := range dir {
aMap[k] = aData[k]
superMap[v] = aMap
}
hello(superMap)
}
func hello(superMap map[string]map[int]string) {
fmt.Printf("superMap of user is %v \n", superMap["user"])
cnt := len(superMap["user"])
if cnt > 1{
fmt.Printf("expected only one value received %v", cnt)
}
}
最佳答案
正如 Arjan 在评论中所说,您需要将 aMap
的创建移动到 for 循环中。原因是,在您发布的原始代码中,您正在处理内存中的一个 aMap
实例。这意味着,只会创建一个名为 aMap
的 map ,当您将另一个变量分配给 aMap
的值时,您就是在分配一个引用。这意味着,任何持有引用(对 aMap
)的变量(对 aMap
)在状态发生变化时,将在所有其他也持有该引用的变量中被观察到,因为它们都解析为内存中的同一个对象。
当 aMap
被移入 for/range 循环时,这意味着将创建 4 个单独的 aMap
实例,它们都有自己的内存。改变其中一个 aMaps
的状态不会影响其他的,因为它们在内存中是它们自己的对象。现在,如果您使用其中一个对象并使用另一个变量再次对其进行引用,那么您最终会遇到与第一种情况相同的情况。
package main
import (
"fmt"
)
func main() {
aData := map[int]string{
0: "apple",
1: "samsung",
2: "htc",
3: "sony",
}
dir := []string{"user", "doc", "bin", "src"}
//aMap := make(map[int]string) //only one map instance is created in memory
superMap := make(map[string]map[int]string)
for k, v := range dir {
//multiple map instances are created in memory
aMap := make(map[int]string)
aMap[k] = aData[k]
superMap[v] = aMap
}
hello(superMap)
}
func hello(superMap map[string]map[int]string) {
fmt.Printf("superMap of user is %v \n", superMap["user"])
cnt := len(superMap["user"])
if cnt > 1 {
fmt.Printf("expected only one value received %v", cnt)
}
}
关于arrays - 如何在 golang 中创建关联映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23064933/