dongzi1397 2014-05-27 21:28
浏览 72
已采纳

Golang Map结构在另一个

I'm new working on golang, In this case I have a map [string] which has a struct. At this point everything is works.

But I would like to have a map[string] in which I can access at the same time to another map[string] which has it self struct.

This is the code in which I'm trying to work.

type myStruct struct{
    atrib1       string
    atrib2       string 

}

var apiRequest map[string] map[string]myStruct

I would like acces to something like this:

func main() {
    apiRequest = make(map[string] map[string]myStruct)

    apiKeyTypeRequest["Key"]["MyFirstOption"].atrib1 = "first Value first op" 
    apiKeyTypeRequest["Key"]["MyFirstOption"].atrib2 = "second Value first op" 
    apiKeyTypeRequest["Key"]["MysecondtOption"].atrib1 = "first Value second op" 

}
  • 写回答

3条回答 默认 最新

  • douzi1350 2014-05-27 22:51
    关注

    An alternative to using a map inside a map, is to have a single map[mapKey] where mapKey is a struct:

    type mapKey struct {
        Key    string
        Option string
    }
    

    The benefits is that you only have to do a single lookup when searching for a myStruct, and you only have to create a single map.
    The downside is in case you need to be able to get that options map[string]myStruct map, since it does not exist. Also, you cannot check if a certain key exists or not, because keys and options exists in pairs.

    Working example:

    package main
    
    import "fmt"
    
    type myStruct struct {
        atrib1 string
        atrib2 string
    }
    
    type mapKey struct {
        Key    string
        Option string
    }
    
    func main() {
        apiKeyTypeRequest := make(map[mapKey]myStruct)
    
        apiKeyTypeRequest[mapKey{"Key", "MyFirstOption"}] = myStruct{"first Value first op", "second Value first op"}
        apiKeyTypeRequest[mapKey{"Key", "MysecondtOption"}] = myStruct{atrib1: "first Value second op"}
    
        fmt.Printf("%+v
    ", apiKeyTypeRequest)
    }
    

    Playground: http://play.golang.org/p/tGd7ja7QI2

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

报告相同问题?

悬赏问题

  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码