繁体   English   中英

Golang接口转换错误:缺少方法

[英]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 Struct有一个嵌入成员实现接口Interface 当我编译这个片段时,我收到一个错误:

panic: interface conversion: main.Struct is not main.Interface: missing method Interface

这似乎不可思议,因为结构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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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