登录
首页 >  Golang >  Go问答

Go 编译器为何无法自动推断结构体实现接口

来源:stackoverflow

时间:2024-02-11 21:15:23 476浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《Go 编译器为何无法自动推断结构体实现接口》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

运行下面的代码将导致编译错误:

不能在返回参数中使用作者(类型 []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)varauthors []namer 就可以了,但我不明白为什么编译器无法推断出 personnamer


正确答案


因为 []person 不是 []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.
}

如果代码期望接收 []namer,那么它必须得到。不是 []concretetypethatimplementsnamer - 它们不可互换。

今天关于《Go 编译器为何无法自动推断结构体实现接口》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>