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

huangapple go评论71阅读模式
英文:

How to implement interface method with return type is an interface in Golang

问题

这是我的代码:

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

我得到了一个错误:

无法将a(类型为*A)用作函数参数中的IA类型:
	*A未实现IA(FB方法的类型错误)
		具有FB() *B
		想要FB() IB

这是完整的代码:http://play.golang.org/p/udhsZgW3W2
我应该编辑IA接口还是修改我的A结构体?
如果我在另一个包中定义IA、IB(这样我可以共享这些接口),我必须导入我的包并将IB用作A.FB()的返回类型,对吗?

英文:

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

得分: 21

只需将

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
}
英文:

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
}

huangapple
  • 本文由 发表于 2012年8月12日 18:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/11921634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定