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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?