亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 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 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號