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?
CodePudding user response:
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)
}
