将一个键/字段追加到一个接口中,该接口是一个映射。

huangapple go评论67阅读模式
英文:

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))

Playground 示例

如果映射可以包含不同的值类型,那么可以使用类型断言来访问该组:

g, ok := outJson["a"].(*Group)
if !ok {
    panic("以更好的方式处理错误")
}
g.Hosts = append(g.Hosts, "hostname")

Playground 示例

英文:

If all you have are Group values, then declare outJson as a map of *Group:

outJson := make(map[string]*Group, len(groups))

Playground Example

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")

Playground Example

huangapple
  • 本文由 发表于 2016年11月10日 08:39:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/40518303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定