gpt4 book ai didi

go - 为什么 Go 认为这个结构不遵守这个接口(interface)?

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:53 25 4
gpt4 key购买 nike

假设我设置了两个 Go 接口(interface)并按如下方式实现它们:

type fooInterface interface {
buildBar() barInterface
}

type barInterface interface {
stuff()
}

type fooStruct struct{}
type barStruct struct{}

func (*fooStruct) buildBar() *barStruct {
return &barStruct{}
}

func (*barStruct) stuff() {}

当我尝试将 fooStruct 分配给 fooInterface 变量时,我收到以下错误:

cannot use fooStruct literal (type *fooStruct) as type fooInterface in assignment:
*fooStruct does not implement fooInterface (wrong type for buildBar method)
have buildBar() *barStruct
want buildBar() barInterface

当然,我可以修改 fooStruct 中的 buildBar() 以返回一个 barInterface 并且它会起作用。但是,我很好奇为什么 Go 在这种情况下没有注意到 *barStruct 遵守 barInterface ,特别是因为这可以在像 Java 这样的语言中工作(可能是因为Java 接口(interface)已明确实现)。

Go Playground 示例:https://play.golang.org/p/84zymo-YnM

最佳答案

go 中的函数类型不是协变的,也不是逆变的。

因此,要可分配,签名必须完全匹配。

引用资料:

关于go - 为什么 Go 认为这个结构不遵守这个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704713/

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