所以,我试图通过搜索和网络搜索找到解决方案。没有成功。这可能是一个简单的解决方案,但是可能我有点搞砸了。
我已经在go playground中准备了以下示例。
// main.go
type myInterface interface {
Function1() string
Function2() int
}
type myStruct struct {
myInterface
// arbitrary implementation
}
func myFunc(val myInterface) {
fmt.Printf("%T %v", val, val)
fmt.Printf("this failes: %q", val.Function1())
// how to safely test,
// whether the underlying value
// has implemented the interface?
}
func main() {
myFunc(&myStruct{})
}
它由接口myInterface
,任意结构myStruct
组成,该结构具有嵌入式接口(但未实际实现)和一些其他任意字段。现在,由于已嵌入接口,因此将该结构注入到myFunc
中,go编译器将接受此结构。但是,如果myFunc
尝试调用该接口的Function,则会感到恐慌–可以理解。]
假设,我不知道实际的struct实现(因为我不受接口实现代码的控制):
我如何可靠地测试给定的基础值是否具有接口定义的方法集(Function1
和Function2
)的实际实现?
我想,这对于reflect
包是可以解决的(这里的性能不是问题)。也许还有其他可行的解决方案?类型断言似乎不适合我...
所以,我试图通过搜索和网络搜索找到解决方案。没有成功。这可能是一个简单的解决方案,但可能我只是一团糟。我准备了以下示例...
当将接口I嵌入到结构中时,这意味着您正在使用类型I定义该结构的成员字段,但是该字段没有名称。如果您需要一个实现接口的字段,则可以将该字段设置为: