How do I create a Go struct something like this,
{Name:Test { App1:Version1 App2:Version2}}
using Go where App1/2
and Version1/2
is dynamic.
I have tried the follwing,
type Final struct {
App string `json:"Name"`
Applications [] Application
}
type final []Final
type Application struct {
App string `json:`
}
final := Final {
Name:"Test",
Applications: []Application{
{GetApps()},
},
}
where GetApps will return a list of App details, instead I would like to have a key value pair where key would be the Appname and value would be its details. I just need a syntax, kindly help
As mentioned, using a map
for Final
's Applications
is likely what you are after.
type Final struct {
Name string `json:"Name"`
Applications map[string]string
}
Then you can assign it as in your attempts:
final := Final{
Name: "Test",
Applications: GetApps(),
}
Make sure GetApps()
returns a map[string]string
and you will have your dynamic keys when json marshalling.
See an example here.
I don't see why you would need anything to be dynamic. This refactor seems to cover your case:
type Application {
Name string
Detail string
}
type Final struct {
Name string
Applications []Application
}
func GetApps() []Application {
// ... Get a slice of Applications
return []Application{}
}
func main() {
final := Final{
Name: "Test",
Applications: []Application{}
}
for _, app := range GetApps() {
final.Applications = append(final.Applications, app)
}
// final is ready
}
Type Application
could also be a map[string]string
like other have mentioned or a struct it doesn't matter because the type is known at compile time and there is no need for dynamic type here.