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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算