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

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

Golang接口轉換錯誤:缺少方法

Golang接口轉換錯誤:缺少方法

Go
Helenr 2022-10-10 10:32:31
看看這個片段:package maintype Interface interface {    Interface()}type Struct struct {    Interface}func main() {    var i interface{} = Struct{}    _ = i.(Interface)}structStruct有一個嵌入的成員實現接口Interface。當我編譯這個片段時,我得到一個錯誤:panic: interface conversion: main.Struct is not main.Interface: missing method Interface這看起來很奇怪,因為 struct應該從嵌入的接口Struct繼承方法。InterfaceInterface我想知道為什么會發生這個錯誤?它是在 golang 中設計的還是只是 golang 編譯器的錯誤?
查看完整描述

1 回答

?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

您不能同時擁有同名的字段和方法,當您嵌入X提供方法的命名時會發生這種情況X()。


如所寫。Struct{}.Interface是一個領域,而不是一個方法。沒有Struct.Interface(),只有Struct.Interface.Interface()。


重命名您的界面。例如,這很好用:


package main


type Foo interface {

    Interface()

}


type Struct struct {

    Foo

}



func main() {

    var i interface{} = Struct{}

    _ = i.(Foo)

}


查看完整回答
反對 回復 2022-10-10
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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