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