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

时间:2012-08-12 10:52:32

标签: 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!"
}

我收到错误:

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(),是不是?

1 个答案:

答案 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
}