简体   繁体   中英

Golang interface conversion error: missing method

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?

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM