go - Golang接口转换错误:缺少方法
问题描述
看看这个片段:
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
这看起来很奇怪,因为 struct应该从嵌入的接口Struct
继承方法。Interface
Interface
我想知道为什么会发生这个错误?它是在 golang 中设计的还是只是 golang 编译器的错误?
解决方案
您不能同时拥有同名的字段和方法,当您嵌入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)
}
推荐阅读
- batch-file - 根据部分文件夹名称递增文件夹名称
- ionic4 - How to change color of button text in popover in ionic 4
- html - justify content center property in bootstrap not working to center contents in a row
- python - Remove a User from GCP project
- sql-server - Unable to bind mount a Windows folder in a Linux SQL Server docker image
- python - 使用绝对值和除以决策变量的成本函数
- javascript - Flatten arrays within object of arrays with data from parent object
- python-3.x - Make discord python rewrite bot tag message author
- python - Python Program counting and list question
- java - i want to read a data from a file in console with bufferreader and vector