为什么Go认为这种结构不符合这个界面?

时间:2017-12-07 22:13:52

标签: go

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

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

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

去游乐场示例:https://play.golang.org/p/84zymo-YnM

1 个答案:

答案 0 :(得分:2)

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

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

参考文献:

相关问题