类型未实现具有接口方法签名的接口

问题描述 投票:0回答:1

情况

  • Bar
    有一个方法
    Get()
    带有签名
    *Foo
  • Foo
    实现了2个接口
    I_Venus1
    I_Mars1
  • I_Venus2
    有一个方法
    Get()
    带有签名
    I_Venus1
  • I_Mars2
    有一个带有签名
    Get()
    的方法
    I_Mars1
type Foo struct {
}

type Bar struct {
}

func (*Bar) Get() *Foo {
    return nil
}

type I_Venus1 interface {
}

type I_Venus2 interface {
    Get() I_Venus1
}

type I_Mars1 interface {
}

type I_Mars2 interface {
    Get() I_Mars1
}

var _ I_Venus1 = &(Foo{}) // Foo meets I_Venus1 interface
var _ I_Mars1 = &(Foo{}) // Foo meets I_Mars1 interface

问题

var _ I_Venus2 = &(Bar{}) // *Bar does not implement I_Venus2 (wrong type for method Get)
var _ I_Mars2 = &(Bar{})  // *Bar does not implement I_Mars2 (wrong type for method Get)

我不明白是什么阻止了 go 编译器决定 Bar 实现了 I_Venus2 和 I_Mars1 接口。

注意:这个问题是

的变体

Go 接口方法返回接口与返回具体类型的方法不匹配

go interface
1个回答
0
投票

@peter 通过指向 go 的常见问题解答提供了很好的答案。

想要协变结果类型的程序员通常会尝试通过接口来表达类型层次结构。在 Go 中,接口和实现之间的清晰分离更为自然。

© www.soinside.com 2019 - 2024. All rights reserved.