我正在尝试在Go中实现一些接口。
我有InterfaceS:
type InterfaceA interface{
read(interface{}) string
}
然后我有InterfaceB:
type InterfaceB interface{
fetch()
}
我有一个功能:
func Read(a InterfaceA) {}
我有StructA,它通过它的方法满足InterfaceA,但它没有变量“interface {}”,而是传递给InterfaceB:
type StructA struct {}
func (a *StructA) read(b InterfaceB) string {
resp := b.fetch()
return resp
}
这似乎适用于我的单元测试,但是当我导入包时,我得到一个错误,指出InterfaceA未正确实现,因为它期望“read(interface {})”而不是“read(InterfaceB)”。错误:
StructA does not implement InterfaceA (wrong type for read method)
have read(InterfaceB) string
want read(interface {}) string
我试图将接口传递给read()函数的原因是我可以模拟出“i.fetch()”方法,但仍然测试read()函数的其余部分。
我也无法传递StructA的读取方法一个接口参数(例如read(b interface{})
,因为那时b
将没有fetch()
方法。
我做错了吗?我认为这在我的单元测试工作中起作用。我只是在导入包时遇到了问题。
感谢您的评论。我已经设法通过类型类型断言使其工作。更多细节可以在这里找到:golang.org/ref/spec#Type_assertions