Why using anonymous field in struct enables the type to satisfy interface when there's no methods written?

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

Why using anonymous field in struct enables the type to satisfy interface when there's no methods written?

问题

对于一个类型来满足一个接口,该类型需要实现接口中定义的方法。

然而,在下面的代码片段中,myStruct 没有实现任何方法,但通过将 someInterface 作为匿名字段使用,它满足了 someInterface 接口。

有人可以帮忙解释为什么会这样吗?谢谢。

package main

import "fmt"

type someInterface interface {
	method1(int) string
	method2(string) string
}

type myStruct struct {
	someInterface
	body int
}

func main() {
	var foo someInterface
	bar := myStruct{}

	foo = bar // 为什么没有编译错误??

	fmt.Println(foo)
}
英文:

For a type to satisfy an interface, the type needs to implement the methods defined in the interface.

However, in the code snippet below, myStruct does not have any methods written, but by using someInterface as anonymous field, it satisfies someInterface.

Can someone help explain why is it? Thank you.

package main

import "fmt"

type someInterface interface {
	method1(int) string
	method2(string) string
}

type myStruct struct {
	someInterface
	body int
}

func main() {
	var foo someInterface
	bar := myStruct{}

	foo = bar // why no compile error??

	fmt.Println(foo)
}

答案1

得分: 2

myStruct嵌入了someInterface,因此它具有该接口中定义的所有方法。这也意味着,myStruct有一个名为someInterface的字段,该字段未初始化,因此调用bar.method1将导致恐慌。在使用之前,您必须对其进行初始化。

bar := myStruct{}
bar.someInterface = someInterfaceImpl{}
bar.method1(0)
bar.method2("")
英文:

myStruct embeds someInterface, so it has all the methods defined in that interface. That also means, myStruct has a field called someInterface, which is not initializes, so calling bar.method1 will panic. You have to initialize it before using it.

bar:=myStruct{}
bar.someInterface=someInterfaceImpl{}
bar.method1(0)
bar.method2("")

huangapple
  • 本文由 发表于 2021年8月8日 02:29:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/68695132.html
匿名

发表评论

匿名网友

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

确定