为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 Go 编译器不能推断结构实现了接口

为什么 Go 编译器不能推断结构实现了接口

Go
子衿沉夜 2022-10-17 10:03:55
运行下面的代码会导致编译错误:不能在返回参数中使用作者(类型 []Person)作为类型 []Namer为什么不能 Go 编译它?type Namer interface {    Name() string}type Person struct {    name string}func (r Person) Name() string {    return r.name}func Authors() []Namer {    // One or the other is used - both are not good:    authors := make([]Person, 10)    var authors []Person    ...    return authors声明authors为authors := make([]Namer, 10)orvar authors []Namer会很好,但我不明白为什么编译器不能推断Person是Namer.
查看完整描述

1 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

因为 a[]Person 不是a []Namer。让我们把你的例子更进一步:


type Namer interface {

    Name() string

}


type Person struct {

    name string

}


func (r Person) Name() string {

    return r.name

}


type Thing struct {

    name string

}


func (t Thing) Name() string {

    return r.name

}


func Authors() []Namer {

    authors := make([]Person, 10)

    return authors

}


func main() {

    namers := Authors()

    // Great! This gives me a []Namer, according to the return type, I'll use it that way!

    thing := Thing{}

    namers := append(namers, thing)

    // This *should* work, because it's supposed to be a []Namer, and Thing is a Namer.

    // But you can't put a Thing in a []Person, because that's a concrete type.

}

如果代码期望收到 a []Namer,那就是它必须得到的。不[]ConcreteTypeThatImplementsNamer- 它们不可互换。


查看完整回答
反对 回复 2022-10-17
  • 1 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信