I want to define a struct completely dynamically, so that I can get the following struct, but without defining it first?
type Data struct {
a string
b int `json:"b"`
}
d := Data{}
I want to define a struct completely dynamically, so that I can get the following struct, but without defining it first?
type Data struct {
a string
b int `json:"b"`
}
d := Data{}
An application can create a struct programmatically using reflect.StructOf, but all fields in the struct must be exported.
The question gets the struct as a value, but it's likely that a pointer to the struct is more useful to the application.
Given the above, this answer shows how to do the following without defining the type at compile time:
type Data struct {
A string `json:"a"`
B int `json:"b"`
}
var d interface{} = &Data{}
The code is:
t := reflect.StructOf([]reflect.StructField{
{
Name: "A",
Type: reflect.TypeOf(int(0)),
Tag: `json:"a"`,
},
{
Name: "B",
Type: reflect.TypeOf(""),
Tag: `json:"B"`,
},
})
d := reflect.New(t).Interface()
Here's a runnable example that sets some fields: https://play.golang.org/p/uik7Ph8_BRH