我需要遍历结构类型的所有字段并检查它们是否实现了给定的接口。
type Model interface {...}
func HasModels(m Model) {
s := reflect.ValueOf(m).Elem()
t := s.Type()
modelType := reflect.TypeOf((*Model)(nil)).Elem()
for i := 0; i < s.NumField(); i++ {
f := t.Field(i)
fmt.Printf("%d: %s %s -> %s\n", i, f.Name, f.Type, f.Type.Implements(modelType))
}
}
然后,如果调用 HasModels 的结构如下:
type Company struct {...}
type User struct {
...
Company Company
}
HasModels(&User{})
公司和用户都实施模型;我得到 f.Type.Implements(ModelType) 为 User 结构的 Company 字段返回 false。
这是出乎意料的,那么,我在这里做错了什么?