这是我的代码:
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(),是不是?
答案 0 :(得分:16)
只需更改
func (a *A) FB() *B {
return a.b
}
到
func (a *A) FB() IB {
return a.b
}
当然IB
可以在另一个包中定义。因此,如果两个接口都在包foo
中定义,并且实现在包bar
中,那么声明是
type IA interface {
FB() IB
}
虽然实施是
func (a *A) FB() foo.IB {
return a.b
}