在 Golang 中反映递归结构

Recursive Struct Reflect in Golang

我有一个嵌套结构定义扁平化成一个切片(这个假设是不可商量的,我必须处理它):

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",
      },
    },
  },
}

并且我想使用递归的方法构建相应的嵌套结构(不知道真正的深度):

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
// })

然后我希望能够分配一些变量的值:

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
// })

设置根级变量值可以,但我无法进入子级并分配任何变量,无论我如何使用reflect ValueOf()/Elem()/Addr()...,这里是一些例子:

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

感谢上面的 mkopriva 评论,我现在明白了我的错误:fieldSub 是一个指针,我应该检查是否为 nil,然后在尝试获取 Elem() 和 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
// })