假设我们有如下代码
package main
type I1 interface {
Foo() string
}
type I2 interface {
Bar() I1
}
type S1 struct{}
func (s *S1) Foo() string {
return "foo"
}
type S2 struct{}
func (s *S2) Bar() *S1 {
return &S1{}
}
func main() {
x := &S2{}
var i I1 = x.Bar()
println(i.Foo())
var y I2
y = &S2{}
println(y.Bar().Foo())
}
现在,在我看来 S2
满足 I2
,因为 Bar()
的返回满足 I1
,如上面几行所示,但编译器不同意我的观点:
# command-line-arguments
./main.go:28:4: cannot use S2 literal (type *S2) as type I2 in assignment:
*S2 does not implement I2 (wrong type for Bar method)
have Bar() *S1
want Bar() I1
是的,我知道它们是不同的类型†,但这不是接口(interface)接受满足其要求的任何类型的要点吗?
谁能提供更多信息,说明现阶段未考虑界面满意度的技术原因是什么?
最佳答案
接口(interface)不满足,方法签名不匹配。接口(interface)中指定的方法签名为: 栏() I1 但提供的方法签名是: 栏() *S1
您仍然可以返回一个指向 S1 实例的指针,但您需要匹配方法签名。将方法的返回类型更改为 I1。
关于go - 为什么返回具体类型不满足需要接口(interface)返回的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55218089/