【发布时间】:2022-03-02 01:13:20
【问题描述】:
reflect.StructField 有一个Index 字段,其类型为[]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():
// 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或只能通过匿名/嵌入式字段访问的字段,我想我应该说。一开始没有考虑嵌入结构的非匿名字段。
标签: reflection go