20
这里的接口是我的代码:如何实现与返回类型接口的方法是在Golang
type IA interface {
FB() IB
}
type IB interface {
Bar() string
}
type A struct {
b *B
}
func (a *A) FB() *B {
return a.b
}
type B struct{}
func (b *B) Bar() string {
return "Bar!"
}
我得到一个错误:
cannot use a (type *A) as type IA in function argument:
*A does not implement IA (wrong type for FB method)
have FB() *B
want FB() IB
下面是完整的代码:http://play.golang.org/p/udhsZgW3W2
我应该编辑IA接口或修改我的A结构?
如果我在其他包中定义IA,IB(所以我可以共享这些接口),我必须导入我的包并使用IB作为A.FB()的返回类型,是不是?
这不回答这个问题。问题在于我们希望将接口放在新文件中而不能更改原始定义。 – epsalon 2017-01-26 00:13:58
@epsalon你的问题与原来的问题有什么关系?请多描述一下。 – Mue 2017-01-26 05:56:29
我认为@ epsalon的问题是相当中肯的。假设A和B都在单独且无法访问的包中定义。如何回顾性地定义接口IA和IB?你可能想要这样做的一个例子是,如果你试图定义这些接口,以便在完全不同的包中为A和B使用mock而不能修改声明A和B的原始文件。 – ishaaq 2017-04-24 19:28:39