看看這個片段:
package main
type 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
這看起來很奇怪,因為 structStruct應該Interface從嵌入的介面繼承方法Interface。
我想知道為什么會發生這個錯誤?它是在golang中設計成這樣還是只是golang編譯器的一個錯誤?
uj5u.com熱心網友回復:
您不能同時擁有同名的欄位和方法,當您嵌入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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/334902.html
標籤:走
