检查struct是否实现了给定的接口

时间:2013-09-02 09:57:41

标签: reflection go

我需要遍历struct类型的所有字段,并检查它们是否实现了给定的接口。

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。

这是出乎意料的,所以,我在这里做错了什么?

1 个答案:

答案 0 :(得分:18)

你遗憾地遗漏了必要的部分(请总是发布完整的程序),所以我只能猜测问题是在指针接收器上定义的方法中,在这种情况下代码的行为是预计。检查此示例及其输出:

package main

import (
        "fmt"
        "reflect"
)

type Model interface {
        m()
}

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 -> %t\n", i, f.Name, f.Type, f.Type.Implements(modelType))
        }
}

type Company struct{}

func (Company) m() {}

type Department struct{}

func (*Department) m() {}

type User struct {
        CompanyA    Company
        CompanyB    *Company
        DepartmentA Department
        DepartmentB *Department
}

func (User) m() {}

func main() {
        HasModels(&User{})
}

Playground


输出:

0: CompanyA main.Company -> true
1: CompanyB *main.Company -> true
2: DepartmentA main.Department -> false
3: DepartmentB *main.Department -> true
相关问题