go - 为什么返回具体类型不满足需要接口(interface)返回的接口(interface)

标签 go interface

假设我们有如下代码

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)接受满足其要求的任何类型的要点吗?

谁能提供更多信息,说明现阶段未考虑界面满意度的技术原因是什么?


Concrete type does not match interface on return type

最佳答案

接口(interface)不满足,方法签名不匹配。接口(interface)中指定的方法签名为: 栏() I1 但提供的方法签名是: 栏() *S1

您仍然可以返回一个指向 S1 实例的指针,但您需要匹配方法签名。将方法的返回类型更改为 I1

关于go - 为什么返回具体类型不满足需要接口(interface)返回的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55218089/

相关文章:

go - 通过 channel 处理 HTTP 请求的模式

Golang 加密消息修复 go-crypt()

c# - 创建动态类型集合和数组

Python继承 - 如何禁用函数

string - Go:理解字符串

Azure WebSocket 无法与 Go httpPlatformHandler 一起使用

去解码图像不支持的类型错误

generics - 带有泛型的 SAM 转换

java - 具有通用参数的接口(interface) - 无法编译

java - compareTo() 方法如何比较字符串?