I have a nested three layer struct. I would like to use reflect in Go to parse it (use recursive function). The reasons to use reflect and the recursive function are
- can have various number of fields (but the first two fields are fixed)
- the field types are not fixed.
- The number of nested layers can be different (in this example only three layers. It can be many more)
Here are some codes.
type Edge struct{
Uid string `json:"uid,omitempty"`
Name string `json:"name,omitempty"`
Read Article `json:"visited,omitempty"`
}
type Article struct {
Uid string`json:"uid,omitempty"`
Namestring`json:"name,omitempty"`
From Site `json:"from,omitempty"`
}
type Site struct{
Uid string `json:"uid,omitempty"`
Name string `json:"name,omitempty"`
}
func CheckNestedStruct(edges interface{}){
rv := reflect.ValueOf(edges).Elem()
uidField := rv.FieldByName("Uid")
uid := getStructField(edges, "Name") // get value of Name from database
if (uid != ""){
uidField.SetString(uid)
}
for i := 0 ; i < rv.NumField() ; i++ {
field := rv.Field(i)
fieldType := field.Kind()
if (fieldType == reflect.Struct){
CheckNestedStruct(field)
}
}
}
func main(){
....
var edges Edges{
...
...
}
CheckNestedStruct(&edges)
}
When I ran this, in the first layer I got "type: *entity.SacWebIS". However, in the second iteration/recursion, I got "type: *reflect.rtype" .
I also tried field.Interface()
.
How to modify this code?
Thanks.
UPDATE
The solution is
CheckNestedStruct(dg, field.Addr().Interface())