duangan6797 2012-08-12 10:52
浏览 253
已采纳

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

Here is my code:

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!"
}

I get an error:

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

Here is the full code: http://play.golang.org/p/udhsZgW3W2
I should edit the IA interface or modifi my A struct?
What if I define IA, IB in a other package (so I can share these interface), I must import my package and use the IB as returned type of A.FB(), is it right?

  • 写回答

1条回答 默认 最新

  • duan117890 2012-08-12 11:59
    关注

    Just change

    func (a *A) FB() *B {
        return a.b
    }
    

    into

    func (a *A) FB() IB {
        return a.b
    }
    

    Surely IB can be defined in another package. So if both interfaces are defined in package foo and the implementations are in package bar, then the declaration is

    type IA interface {
        FB() IB
    }
    

    while the implementation is

    func (a *A) FB() foo.IB {
        return a.b
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数