dongwei4444 2018-02-05 17:09
浏览 34
已采纳

在go结构中初始化深层地图嵌套

To initialize a map in a struct one should do the following:

someStruct.nestedMap = make(map[int8]int8)

But what should you do if you have a code structure like this:

type Base struct {
    base map[int8]uint64
}

type Middle struct {
    baseObjects map[int8]Base
}

type Top struct {
    middleObjects map[int8]Middle
}

There we have a total of 3 structs where each has a struct as a key. How do you initialize this, and make it ready to go?

  • 写回答

2条回答 默认 最新

  • donglong9745 2018-02-06 17:55
    关注

    What you want is auctually a map with default value that is not zero value, but a value ready to use, in this case, a made map.

    Before going to the solution, there auctually is an issue about go here: https://github.com/golang/go/issues/3117

    For reasons, Go now does not support to assign to a field of a struct if the struct is stored in a map.

    To solve the issue, you need to use a pointer to that struct, and store the pointer in the map instead. So your data structure needs to be changed like:

    type Base struct {
        base map[int8]uint64
    }
    
    type Middle struct {
        baseObjects map[int8]*Base
    }
    
    type Top struct {
        middleObjects map[int8]*Middle
    }
    

    And to the core logic: a defualt value map. Go does not support that with plain maps, but we can extend it, using methods to wrap it around.

    func (t Top) Get(i int8) *Middle {
        x, ok := t.middleObjects[i]
        if !ok {
            v := NewMiddle()
            t.middleObjects[i] = v
            return v
        }
    
        return x
    }
    
    func (m Middle) Get(i int8) *Base {
        x, ok := m.baseObjects[i]
        if !ok {
            v := NewBase()
            m.baseObjects[i] = v
            return v
        }
    
        return x
    }
    

    When we are trying to get a value, we first check if it exists. If not, we return a new constructed one, and if it did exist, return the value.

    Usage:

    t.Get(8).Get(9).base[10] = 14
    

    Playground example: https://play.golang.org/p/0JSN0yjRPif

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题