英文:
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("")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论