英文:
Golang interface conversion error: missing method
问题
看一下这段代码:
package main
type Interface interface {
Interface()
}
type Struct struct {
Interface
}
func main() {
var i interface{} = Struct{}
_ = i.(Interface)
}
结构体 Struct
嵌入了实现接口 Interface
的成员。当我编译这段代码时,我得到了一个错误:
panic: interface conversion: main.Struct is not main.Interface: missing method Interface
这看起来很奇怪,因为结构体 Struct
应该从嵌入的接口 Interface
继承了方法 Interface
。
我想知道为什么会出现这个错误?这是 golang 的设计如此,还是只是 golang 编译器的一个 bug?
英文:
Look at this snippet:
package main
type Interface interface {
Interface()
}
type Struct struct {
Interface
}
func main() {
var i interface{} = Struct{}
_ = i.(Interface)
}
struct Struct
has a embeded member implements interface Interface
. When I compile this snippet, I get an error:
panic: interface conversion: main.Struct is not main.Interface: missing method Interface
This seems weird because struct Struct
should inherit method Interface
from the embeded interface Interface
.
I want to know why this error happens? Is it designed as this in golang or is it just a bug of golang compiler?
答案1
得分: 3
你不能同时拥有一个字段和一个同名的方法,当你嵌入一个名为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)
}
英文:
You can't have both a field and a method with the same name, which is what happens when you embed something named X
that provides a method X()
.
As written. Struct{}.Interface
is a field, not a method. There is no Struct.Interface()
, only Struct.Interface.Interface()
.
Rename your interface. For example, this works fine:
package main
type Foo interface {
Interface()
}
type Struct struct {
Foo
}
func main() {
var i interface{} = Struct{}
_ = i.(Foo)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论