首页 > 解决方案 > 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继承方法。InterfaceInterface

我想知道为什么会发生这个错误?它是在 golang 中设计的还是只是 golang 编译器的错误?

标签: go

解决方案


您不能同时拥有同名的字段和方法,当您嵌入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)
}

推荐阅读