登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-13 15:42:23 147浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《Golang接口转换错误:缺少方法》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

看看这个片段:

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 struct 应该从嵌入接口 interface 继承方法 interface

我想知道为什么会出现这个错误? golang中是这样设计的还是只是golang编译器的一个bug?


正确答案


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

好了,本文到此结束,带大家了解了《Golang接口转换错误:缺少方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>