reflect.StructField有一个Index键入的字段[]int。关于此的文档有点令人困惑:
Index []int // index sequence for Type.FieldByIndex
Run Code Online (Sandbox Code Playgroud)
当然,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
Run Code Online (Sandbox Code Playgroud)
但是,还有Type.Field():
// Field returns a struct type's i'th field.
// It panics if the type's Kind is not Struct.
// It panics if i is not in the range [0, NumField()).
Field(i int) StructFiel
Run Code Online (Sandbox Code Playgroud)
所以他们各自的行为是非常清楚的。
我的问题: a 到底适用于哪些字段/reflect.StructField什么Index情况len(field.Index) > 1?这是为了支持枚举嵌入字段(可通过父级中的匿名字段访问)吗?其他情况下也会出现这种情况吗?(即假设如果!field.Anonymous,那么我们可以将其用作 的field.Index[0]参数吗Field(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
}
Run Code Online (Sandbox Code Playgroud)