Dictionary 基于过滤条件构建地图
我有下面的结构Dictionary 基于过滤条件构建地图,dictionary,go,Dictionary,Go,我有下面的结构 type ModuleList []Module type Module struct { Id string Items []Item Env map[string]string } type Item struct { Id string Host string } 我有一个返回模块列表的服务;但是我想创建一个函数,它可以基于模块
type ModuleList []Module
type Module struct {
Id string
Items []Item
Env map[string]string
}
type Item struct {
Id string
Host string
}
我有一个返回模块列表的服务;但是我想创建一个函数,它可以基于模块Env键值对模块列表进行分组,并返回map[string]ModuleList或map[string]*Module
我可以有任何这样做的示例函数吗
我试过这么做
appsByGroup := make(map[string]ModuleList)
for _, app := range apps {
if _, ok := app.Env["APP_GROUP"]; ok {
appGroup := app.Env["APP_GROUP"]
appsByGroup[appGroup] = app
}
}
);但是不太清楚如何将元素添加到数组中如果您想按
应用程序组对所有模块
进行分组
,那么您是非常正确的。您只是没有正确地附加到切片:
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)
}
}
现在,您可以通过以下方式访问组中的所有模块
(存储在片中):
// returns slice of modules (as ModuleList) with
// Env["APP_GROUP"] == group
appGroups[group]
更新了我在inlineRemoved中的操作删除了我的下一票和关闭标志