英文:
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 "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
答案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("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
// })
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论