递归结构在Golang中的反射

huangapple go评论83阅读模式
英文:

Recursive Struct Reflect in Golang

问题

我有一个嵌套的结构定义,被展开成一个切片(这个假设是不可商议的,我必须处理它):

type element struct {
  Name string
  Type string // 可以是基本类型字符串(例如 "uint8")
              // 或者是嵌套结构的 definition.ID
}
type definition struct {
  ID       string
  Elements []element
}
type definitions []definition
allDefs := definitions{
  {
    ID: "root",
    Elements: []element{
      {
        Name: "SubStruct",
        Type: "sub1", // 这是对另一个定义的引用
      },
      {
        Name: "VarU32",
        Type: "uint32", // 这是基本类型字符串表示
      },
    },
  },
  {
    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 { // 找到对定义的引用
      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()
    }
  }
  // 没有找到对定义的引用,应该是基本类型
  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()
  }
  // 忽略 id 可能是其他任何值的情况
  return nil
}

root := allDefs.getStruct("root")
// 使用 spew 检查变量: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
英文:

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 &quot;uint8&quot;)
              // or a definition.ID for nested struct
}
type definition struct {
  ID       string
  Elements []element
}
type definitions []definition
allDefs := definitions{
  {
    ID: &quot;root&quot;,
    Elements: []element{
      {
        Name: &quot;SubStruct&quot;,
        Type: &quot;sub1&quot;, // this is reference to another definition
      },
      {
        Name: &quot;VarU32&quot;,
        Type: &quot;uint32&quot;, // this is a basic type string representation
      },
    },
  },
  {
    ID: &quot;sub1&quot;,
    Elements: []element{
      {
        Name: &quot;VarU8&quot;,
        Type: &quot;uint8&quot;,
      },
      {
        Name: &quot;VarU16&quot;,
        Type: &quot;uint16&quot;,
      },
    },
  },
}

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:  &quot;&quot;,
        })
      }
      return reflect.New(reflect.StructOf(fields)).Interface()
    }
  }
  // didn&#39;t found a reference to a definition, it should be a basic type
  if id == &quot;uint8&quot; {
    return reflect.ValueOf(uint8(0)).Interface()
  }
  if id == &quot;uint16&quot; {
    return reflect.ValueOf(uint16(0)).Interface()
  }
  if id == &quot;uint32&quot; {
    return reflect.ValueOf(uint32(0)).Interface()
  }
  // ignore the fact id could be anything else for this example
  return nil
}

root := allDefs.getStruct(&quot;root&quot;)
// 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 })(&lt;nil&gt;),
//  VarU32: (uint32) 0
// })

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

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

rootValElem.FieldByName(&quot;VarU32&quot;).SetUint(1)
spew.Dump(root)
// (*struct { SubStruct *struct { VarU8 uint8; VarU16 uint16 }; VarU32 uint32 })(0xc00004e400)({
//  SubStruct: (*struct { VarU8 uint8; VarU16 uint16 })(&lt;nil&gt;),
//  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(&quot;SubStruct&quot;)
// fieldSub.Kind() : ptr
// fieldSub.CanSet() : true

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

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

答案1

得分: 1

感谢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
// })
英文:

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(&quot;SubStruct&quot;)
// fieldSub.Kind() : ptr
// fieldSub.CanSet() : true
// fieldSub.IsNil() : true

if fieldSub.IsNil() &amp;&amp; fieldSub.CanSet() {
  fieldSub.Set(reflect.New(fieldSub.Type().Elem()))
}

fieldU8 := fieldSub.Elem().FieldByName(&quot;VarU8&quot;)
// 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
// })

huangapple
  • 本文由 发表于 2021年12月23日 17:00:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/70459774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定