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

huangapple go评论84阅读模式
英文:

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 嵌入了实现接口 Interface 的成员。当我编译这段代码时,我得到了一个错误:

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

这看起来很奇怪,因为结构体 Struct 应该从嵌入的接口 Interface 继承了方法 Interface

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

英文:

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?

答案1

得分: 3

你不能同时拥有一个字段和一个同名的方法,当你嵌入一个名为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)
}
英文:

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

huangapple
  • 本文由 发表于 2021年10月21日 10:49:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/69655263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定