是否可以接收实现某个接口的所有结构?

时间:2013-03-10 09:56:01

标签: reflection go

我检查了reflect包文档,但没有找到任何内容。我要做的是找到实现接口x的所有结构。然后遍历所有结构以执行操作y。

2 个答案:

答案 0 :(得分:3)

使用带有这样的接口的类型断言(playground link)。我假设你有一些struct个实例(可能在[]interface{}中,如下例所示)。

package main

import "fmt"

type Zapper interface {
    Zap()
}

type A struct {
}

type B struct {
}

func (b B) Zap() {
    fmt.Println("Zap from B")
}

type C struct {
}

func (c C) Zap() {
    fmt.Println("Zap from C")
}

func main() {
    a := A{}
    b := B{}
    c := C{}
    items := []interface{}{a, b, c}
    for _, item := range items {
        if zapper, ok := item.(Zapper); ok {
            fmt.Println("Found Zapper")
            zapper.Zap()
        }
    }
}

您还可以define the interface on the fly并在循环中使用item.(interface { Zap() }),如果它是一次性的,您喜欢这种风格。

答案 1 :(得分:2)

这不能在运行时完成,而只能通过检查程序包(以及递归的所有导入)进行静态处理。或者通过静态检查生成的。{o,a}文件。

但是,可以手动构建满足接口的类型列表(不仅限于结构,为什么?):

if _, ok := concreteInstance.(concreteInterface); ok {
        // concreteInstance satisfies concreteInterface
}