gpt4 book ai didi

interface - 如何实现带返回类型的接口(interface)方法是Golang中的一个接口(interface)

转载 作者:IT老高 更新时间:2023-10-28 13:01:38 27 4
gpt4 key购买 nike

这是我的代码:

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 接口(interface)还是修改我的 A 结构?
如果我在其他包中定义IA、IB(这样我可以共享这些接口(interface)),我必须导入我的包并将IB作为A.FB()的返回类型,对吗?

最佳答案

改变一下

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

进入

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

IB当然可以在另一个包中定义。因此,如果两个接口(interface)都在包 foo 中定义并且实现在包 bar 中,那么声明是

type IA interface {
FB() IB
}

虽然实现是

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

关于interface - 如何实现带返回类型的接口(interface)方法是Golang中的一个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11921634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com