donglang1894 2016-07-14 18:10
浏览 30
已采纳

根据过滤条件去lang构造地图

I have below structures

type ModuleList []Module

type Module struct {
    Id                  string
    Items               []Item
    Env                 map[string]string
}

type Item struct {
    Id    string
    Host  string
}

I have a service which returns ModuleList; but I would like to create a function which can group ModuleList based on Module Env key value and return map[string]ModuleList or map[string]*Module

Can i have any sample function which does this ?

I had tried doing this

appsByGroup := make(map[string]ModuleList)
    for _, app := range apps {
        if _, ok := app.Env["APP_GROUP"]; ok {
            appGroup := app.Env["APP_GROUP"]
            appsByGroup[appGroup] = app
        }
    }

; but not quite sure how to add element to an array

  • 写回答

1条回答 默认 最新

  • dtrovwl75780 2016-07-14 19:21
    关注

    If you want to group all the Modules by a APP_GROUP then you are pretty much correct. You are just not appending to the slice correctly:

    appsByGroup := make(map[string]ModuleList)
    for _, app := range apps {
        if _, ok := app.Env["APP_GROUP"]; ok {
            appGroup := app.Env["APP_GROUP"]
            // app is of type Module while in appsGroup map, each string
            // maps to a ModuleList, which is a slice of Modules.
            // Hence your original line
            // appsByGroup[appGroup] = app would not compile
            appsByGroup[appGroup] = append(appsByGroup[appGroup], app)
        }
    }
    

    Now you can access all the Modules (stored in a slice) in a group by using:

    // returns slice of modules (as ModuleList) with
    // Env["APP_GROUP"] == group
    appGroups[group]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站