gostructreflect

Recursive Struct Reflect in Golang


I have a nested structure definition flatened into a slice (this hypothesis is not negociable, I have to deal with it) :

type element struct {
  Name string
  Type string // can be basic type string (eg "uint8")
              // or a definition.ID for nested struct
}
type definition struct {
  ID       string
  Elements []element
}
type definitions []definition
allDefs := definitions{
  {
    ID: "root",
    Elements: []element{
      {
        Name: "SubStruct",
        Type: "sub1", // this is reference to another definition
      },
      {
        Name: "VarU32",
        Type: "uint32", // this is a basic type string representation
      },
    },
  },
  {
    ID: "sub1",
    Elements: []element{
      {
        Name: "VarU8",
        Type: "uint8",
      },
      {
        Name: "VarU16",
        Type: "uint16",
      },
    },
  },
}

And I would like to build the corresponding nested struct using a recursive method (don't know the real depth) :

func (defs definitions) getStruct(id string) interface{} {
  for _, def := range defs {
    if def.ID == id { // found a reference to definition
      fields := []reflect.StructField{}
      for _, e := range def.Elements {
        s := defs.getStruct(e.Type)
        fields = append(fields, reflect.StructField{
          Name: e.Name,
          Type: reflect.TypeOf(s),
          Tag:  "",
        })
      }
      return reflect.New(reflect.StructOf(fields)).Interface()
    }
  }
  // didn't found a reference to a definition, it should be a basic type
  if id == "uint8" {
    return reflect.ValueOf(uint8(0)).Interface()
  }
  if id == "uint16" {
    return reflect.ValueOf(uint16(0)).Interface()
  }
  if id == "uint32" {
    return reflect.ValueOf(uint32(0)).Interface()
  }
  // ignore the fact id could be anything else for this example
  return nil
}

root := allDefs.getStruct("root")
// using spew to inspect variable : github.com/davecgh/go-spew/spew
spew.Dump(root)
// (*struct { SubStruct *struct { VarU8 uint8; VarU16 uint16 }; VarU32 uint32 })(0xc00004e400)({
//  SubStruct: (*struct { VarU8 uint8; VarU16 uint16 })(<nil>),
//  VarU32: (uint32) 0
// })

Then I want to be able to assign some variable's values :

rootValElem := reflect.ValueOf(root).Elem()

rootValElem.FieldByName("VarU32").SetUint(1)
spew.Dump(root)
// (*struct { SubStruct *struct { VarU8 uint8; VarU16 uint16 }; VarU32 uint32 })(0xc00004e400)({
//  SubStruct: (*struct { VarU8 uint8; VarU16 uint16 })(<nil>),
//  VarU32: (uint32) 1
// })

Setting root level variable value is OK, but I am unable to entering Sub level and assign any variable, no matter how I play with reflect ValueOf()/Elem()/Addr()..., here are some examples :

fieldSub := rootValElem.FieldByName("SubStruct")
// fieldSub.Kind() : ptr
// fieldSub.CanSet() : true

subVal := reflect.ValueOf(fieldSub)
// subVal.Kind() : struct
// subVal.CanSet() : false
fieldU16 := subVal.FieldByName("VarU16")
// fieldU16.Kind() : invalid
// fieldU16.CanSet() : false

fieldSubElem := fieldSub.Elem()
// fieldSubElem.Kind() : invalid
// fieldSubElem.CanSet() : false
fieldU16 := fieldSubElem.FieldByName("VarU16")
// panic: reflect: call of reflect.Value.FieldByName on zero Value

Solution

  • Thanks to mkopriva comment above, I understand now my mistake : fieldSub is a pointer and I should check if nil, then allocate the struct value before trying to get Elem() then Field :

    fieldSub := rootValElem.FieldByName("SubStruct")
    // fieldSub.Kind() : ptr
    // fieldSub.CanSet() : true
    // fieldSub.IsNil() : true
    
    if fieldSub.IsNil() && fieldSub.CanSet() {
      fieldSub.Set(reflect.New(fieldSub.Type().Elem()))
    }
    
    fieldU8 := fieldSub.Elem().FieldByName("VarU8")
    // fieldSub.Kind() : uint8
    // fieldSub.CanSet() : true
    
    if fieldU8.CanSet() {
      fieldU8.SetUint(8)
    }
    
    spew.Dump(root)
    // (*struct { SubStruct *struct { VarU8 uint8; VarU16 uint16 }; VarU32 uint32 })(0xc00008a3f0)({
    //  SubStruct: (*struct { VarU8 uint8; VarU16 uint16 })(0xc0000ac430)({
    //   VarU8: (uint8) 8,
    //   VarU16: (uint16) 0
    //  }),
    //  VarU32: (uint32) 1
    // })