2013-03-10 42 views
1

我检查了reflect软件包的文档,但没有找到任何东西。我想要做的是找到所有结构,实现接口x。然后迭代所有的结构来执行一个动作y。是否可以接收实现某个接口的所有结构?

+0

我怀疑这是可能的。根据我所了解的有关接口的实现,该信息不会在运行时保存。 – fuz 2013-03-10 14:14:35

回答

2

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

然而,一个可以手动生成的类型满足的接口列表(不仅限于结构,为什么?):

if _, ok := concreteInstance.(concreteInterface); ok { 
     // concreteInstance satisfies concreteInterface 
} 
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() })的循环,而不是它是否是一次性的,你喜欢这种样式。

相关问题