What is the best way to fill a struct that has lots of nested structs inside it? I made a struct to generate a json schema file from it that looks like this:
type Schema struct {
Schema string `default:"http://json-schema.org/draft-04/schema#"`
Title string `default:"Test Schema"`
Type string `default:"object"`
AdditionalProperties bool `default:false`
Properties struct {
Core struct {
Type string
AdditionalProperties bool
Properties struct{}
}
Work struct {
Type string
AdditionalProperties bool
Properties struct{}
}
}
}
At first, I wanted to put the default data in tags and fill the struct from that, but reflect
package doesn't look inside the nested structs.
Here is what I did using reflect
:
t := reflect.TypeOf(Schema{})
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
tag := field.Tag.Get("default")
}
The best way to do this is with a constructor method. This will be more readable, and much faster, than using tags plus reflection. Something like:
func NewSchema() *Schema {
return &Schema{
Schema: "http://json-schema.org/draft-04/schema#",
...
}
}