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

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

該方法不應該明確地與接口的簽名簽約嗎?

該方法不應該明確地與接口的簽名簽約嗎?

Go
慕萊塢森 2023-06-12 16:57:21
我剛接觸golang,不太明白為什么下面的demo程序可以執行成功,type fake interface {    getAge(valueInt int,  valStr string) (age int, name string, err error)}type Foo struct {    name string}func (b *Foo) getAge(valueInt int, valStr string) (age int, retErr error) {    age = valueInt    return age, nil}func main() {    inst := &Foo{name:"foo"}    value, _ := inst.getAge(2, "foo")    fmt.Println(value)}接口要返回三個值,但方法getAge只返回兩個,但它仍然有效。如何理解 golang 中的這種行為?謝謝!
查看完整描述

1 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

Foo不執行fake。如果您稍微擴展您的代碼示例(在 Go 操場上嘗試),這是顯而易見的:

package main


import "fmt"


type fake interface {

    getAge(valueInt int, valStr string) (age int, name string, err error)

}


type Foo struct {

    name string

}


func (b *Foo) getAge(valueInt int, valStr string) (age int, retErr error) {

    age = valueInt

    return age, nil

}



func bar(f fake) {

  _, name, _ := f.getAge(10, "")

}


func main() {

    inst := &Foo{name: "foo"}

    value, _ := inst.getAge(2, "foo")

    fmt.Println(value)


    bar(inst)

}

這會產生一個非常具有描述性的編譯錯誤:


prog.go:28:5: cannot use inst (type *Foo) as type fake in argument to bar:

    *Foo does not implement fake (wrong type for getAge method)

        have getAge(int, string) (int, error)

        want getAge(int, string) (int, string, error)


查看完整回答
反對 回復 2023-06-12
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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