如何用返回类型实现接口方法是Golang中的一个接口

nvc*_*nvn 26 interface go

这是我的代码:

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)

  • 我认为@ epsalon的问题非常贴切.假设A和B都是在一个独立且无法访问的包中定义的.如何回顾性地定义接口IA和IB?您可能希望这样做的一个示例是,如果您尝试定义这些接口,以便在完全不同的包中对A和B使用模拟,而无法修改声明A和B的原始文件. (6认同)
  • 这不能回答问题。问题是我们希望将接口包含在新文件中,而又不能更改原始定义。 (3认同)