arrays - 如何在 golang 中创建关联映射?

标签 arrays go

我正在尝试创建“关联” 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)
    }
}

Play

最佳答案

正如 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/

相关文章:

php - Laravel 将动态输入数据数组保存到数据库中

javascript - 查找数组中重复字符的唯一索引

go - 使用模块跟踪依赖项的 Go 项目的包布局?

json - 去 json.Unmarshal 接口(interface)一些子句消失了

Gorilla WebSocket WriteMessage 错误 - Go Lang

postgresql - 将客户端 UUID 转换为 SQL UUID

php - 多维数组到单数组

java - 测试 toString 但失败?

c - 通过结构别名数组

go - 如何编译不符合 `go get`模式的go代码