英文:
go append to an interface key/field which is a map
问题
我的问题是关于向一个接口的字段/键中添加映射的问题。这是为了构建一个JSON对象所必需的。我正在使用map[string]interface{}
来能够向其中添加任何结构类型。我不确定这是否是正确的方法,因为我还在学习Go,但我找不到更好的方法。以下是一个playground的链接:
https://play.golang.org/p/cxpSep8OQD。
我认为我需要使用类型追加,但我不明白如何做。任何帮助都将是有用的。
英文:
My question is about appending to a map which is a filed/key of an interface. This is required to build a JSON object. I am using map[string]interface{}
to be able to append any struct types to it. I am not sure if that is a right way as I am still learning Go but I could not find a better way. Below is a link to a playground:
https://play.golang.org/p/cxpSep8OQD.
I think I need to use type accretion but I do not understand how. Any help would be useful.
答案1
得分: 0
如果你只有Group
值,那么将outJson
声明为*Group
的映射:
outJson := make(map[string]*Group, len(groups))
如果映射可以包含不同的值类型,那么可以使用类型断言来访问该组:
g, ok := outJson["a"].(*Group)
if !ok {
panic("以更好的方式处理错误")
}
g.Hosts = append(g.Hosts, "hostname")
英文:
If all you have are Group
values, then declare outJson
as a map of *Group
:
outJson := make(map[string]*Group, len(groups))
If the map can contain different value types, then use a type assertion to access the group:
g, ok := outJson["a"].(*Group)
if !ok {
panic("handle error a better way")
}
g.Hosts = append(g.Hosts, "hostname")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论