是否可以接收实现某个接口的所有结构?
答
这不能在运行时完成,但只能静态地通过检查程序包(以及递归的所有导入)来完成。或者通过静态检查生成的{o,a}文件。
然而,一个可以手动生成的类型满足的接口列表(不仅限于结构,为什么?):
if _, ok := concreteInstance.(concreteInterface); ok {
// concreteInstance satisfies concreteInterface
}
答
使用类型断言,像这样的接口(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() })
的循环,而不是它是否是一次性的,你喜欢这种样式。
我怀疑这是可能的。根据我所了解的有关接口的实现,该信息不会在运行时保存。 – fuz 2013-03-10 14:14:35