Reflection Go reflect字段索引-单个索引与切片
Reflection Go reflect字段索引-单个索引与切片,reflection,go,Reflection,Go,reflect.StructField有一个键入[]int的索引字段。关于这一点的文件有点混乱: Index []int // index sequence for Type.FieldByIndex 当然,Type.FieldByIndex也像预期的那样,对其行为进行了更清晰的解释: // FieldByIndex returns the nested field corresponding // to the index sequence. It
reflect.StructField
有一个键入[]int
的索引
字段。关于这一点的文件有点混乱:
Index []int // index sequence for Type.FieldByIndex
当然,Type.FieldByIndex
也像预期的那样,对其行为进行了更清晰的解释:
// FieldByIndex returns the nested field corresponding
// to the index sequence. It is equivalent to calling Field
// successively for each index i.
// It panics if the type's Kind is not Struct.
FieldByIndex(index []int) StructField
但是,还有Type.Field()
:
所以他们各自的行为是非常清楚的
我的问题是:
结构域
的索引
与len(field.Index)>1
对应的具体字段/情况是什么?这是否支持枚举嵌入字段(可通过父级中的匿名字段访问)?在其他情况下会发生这种情况吗?(即,如果假设!field.Anonymous
,那么我们可以使用field.Index[0]
作为字段(i int)
的参数。)它可以递归地引用嵌入或非嵌入结构中的字段:
type Foo struct {
Bar string
}
type Baz struct {
Zoo Foo
}
func main() {
b := Baz{Zoo:Foo{"foo"}}
v := reflect.ValueOf(b)
fmt.Println(v.FieldByIndex([]int{0})) //output: <main.Foo Value>
fmt.Println(v.FieldByIndex([]int{0, 0})) //output: foo
}
类型Foo struct{
棒串
}
Baz型结构{
动物园福
}
func main(){
b:=Baz{Zoo:Foo{“Foo}}
v:=反射值(b)
fmt.Println(v.FieldByIndex([]int{0}))//输出:
fmt.Println(v.FieldByIndex([]int{0,0}))//输出:foo
}
它可以递归地引用嵌入或非嵌入结构中的字段:
type Foo struct {
Bar string
}
type Baz struct {
Zoo Foo
}
func main() {
b := Baz{Zoo:Foo{"foo"}}
v := reflect.ValueOf(b)
fmt.Println(v.FieldByIndex([]int{0})) //output: <main.Foo Value>
fmt.Println(v.FieldByIndex([]int{0, 0})) //output: foo
}
类型Foo struct{
棒串
}
Baz型结构{
动物园福
}
func main(){
b:=Baz{Zoo:Foo{“Foo}}
v:=反射值(b)
fmt.Println(v.FieldByIndex([]int{0}))//输出:
fmt.Println(v.FieldByIndex([]int{0,0}))//输出:foo
}
以下是一个示例。为了回答这个问题,我深入研究了反射测试
主程序包
进口(
“fmt”
“反映”
)
类型(
条形结构{
Val字符串
}
Foo结构{
酒吧
}
)
func main(){
t:=reflect.TypeOf(Foo{})
f、 _u:=t.FieldByName(“Val”)
fmt.Println(f.Index)/[0]
}
以下是一个示例。为了回答这个问题,我深入研究了反射测试
主程序包
进口(
“fmt”
“反映”
)
类型(
条形结构{
Val字符串
}
Foo结构{
酒吧
}
)
func main(){
t:=reflect.TypeOf(Foo{})
f、 _u:=t.FieldByName(“Val”)
fmt.Println(f.Index)/[0]
}
谢谢。。。不过,正如我所说,这些文档很清楚,我理解FieldByIndex()
的作用。我的问题是关于reflect.StructField
的索引
字段的-请看问题的最后两句。@BadZen我刚才给了你一个如何将其用于非嵌入式结构的示例。但是你应该可以使用一个索引。谢谢。。。不过,正如我所说,这些文档很清楚,我理解FieldByIndex()
的作用。我的问题是关于reflect.StructField
的索引
字段的-请看问题的最后两句。@BadZen我刚才给了你一个如何将其用于非嵌入式结构的示例。但是您应该可以使用单个索引……!field.Anonymous
或只能通过匿名/嵌入字段访问的字段,我想我应该这么说。起初没有考虑嵌入结构的非匿名字段…<代码>!field.Anonymous或只能通过匿名/嵌入字段访问的字段,我想我应该这么说。最初没有考虑嵌入结构的非匿名字段。