这是我的代码:
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!"
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
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
Run Code Online (Sandbox Code Playgroud)
这是完整的代码:http://play.golang.org/p/udhsZgW3W2
我应该编辑IA界面还是修改我的A结构?
如果我在另一个包中定义IA,IB(所以我可以共享这些接口),我必须导入我的包并使用IB作为A.FB()的返回类型,是不是?
the*_*mue 17
只是改变
func (a *A) FB() *B {
return a.b
}
Run Code Online (Sandbox Code Playgroud)
成
func (a *A) FB() IB {
return a.b
}
Run Code Online (Sandbox Code Playgroud)
当然IB可以在另一个包中定义.因此,如果两个接口都在包中定义,foo并且实现在包中bar,那么声明就是
type IA interface {
FB() IB
}
Run Code Online (Sandbox Code Playgroud)
而实施则是
func (a *A) FB() foo.IB {
return a.b
}
Run Code Online (Sandbox Code Playgroud)