加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 19:21:00 所属栏目:大数据 来源:网络整理
导读:这是我的代码: 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 i
这是我的代码:
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()的返回类型,是吗?

只是改变
func (a *A) FB() *B {
    return a.b
}

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

当然可以在另一个包中定义IB.所以如果两个接口都是在包foo中定义的,并且这些实现是在package bar中的,那么声明是

type IA interface {
    FB() IB
}

而实施是

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读