reflect.StructField
具有一个类型为[]int
的Index
字段。关于此的文档略微令人困惑:
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()
:
// 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
因此,它们的行为分别非常清晰。
我的问题是:在哪些领域/什么情况下,reflect.StructField
的 Index
会具有 len(field.Index) > 1
?这是为了支持枚举嵌入字段(通过父级中的匿名字段可访问)吗?是否会发生其他情况?(即,如果 !field.Anonymous
,那么我们可以安全地假设只需使用 field.Index[0]
作为 Field(i int)
的参数吗?)
!field.Anonymous
或者是只能通过匿名/嵌入字段到达的字段,我想我应该这样说。起初没有考虑到嵌入结构的非匿名字段。 - BadZen