登录
首页 >  Golang >  Go问答

递归结构在 Golang 中的体现

来源:stackoverflow

时间:2024-04-08 19:57:32 154浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《递归结构在 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 })(),
//  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 })(),
//  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
// })

今天关于《递归结构在 Golang 中的体现》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>