英文:
Can One Embed A Struct In A Struct To Satisfy An Interface
问题
我有以下代码(也可以在Go Playground中找到)。是否可能实例化一个包含嵌入式C、S和X的A结构体?我使用接口的原因是,根据我调用的Build函数,我希望拥有具有不同Bar()实现的结构体。我可以有一个S1或S2,其中Bar()略有不同,但都是S'ers。
package main
import "fmt"
type Cer interface {
Foo()
}
type Ser interface {
Bar()
}
type Aer interface {
Cer
Ser
}
type C struct {
CField string
}
func (this *C) Foo() {
}
type S struct {
SField string
}
func (this *S) Bar() {
}
type X struct {
XField string
}
type A struct {
Cer
Ser
X
}
func main() {
x := new(X)
a := Build(x)
fmt.Println(a)
}
func Build(x *X) A {
a := new(A)
a.X = *x
a.XField = "set x"
return *a
}
英文:
I have the following code (also available in the Go Playground). Is it possible to instantiate an A struct such that it contains an embedded C, S and an X. The reason I am using interfaces is because, depending on the Build function I call, I'd like to have structs that have different implementations of Bar(). I could have an S1 or an S2, where Bar() is slightly different, but both are S'ers.
package main
import "fmt"
type Cer interface {
Foo()
}
type Ser interface {
Bar()
}
type Aer interface {
Cer
Ser
}
type C struct {
CField string
}
func (this *C) Foo() {
}
type S struct {
SField string
}
func (this *S) Bar() {
}
type X struct {
XField string
}
type A struct {
Cer
Ser
X
}
func main() {
x := new(X)
a := Build(x)
fmt.Println(a)
}
func Build(x *X) A {
a := new(A)
a.X = *x
a.XField = "set x"
return *a
}
答案1
得分: 1
简短回答是:是的,你可以。
但是,当嵌入接口时,如果在调用嵌入的方法之前没有先给定一个值,你将会遇到运行时错误。
所以,下面的代码是正确的:
a := Build(x)
// 如果删除下面这行代码,在调用 a.Foo() 时将会导致运行时错误
a.Cer = &C{"The CField"}
a.Foo()
英文:
Short answer is: Yes, you can.
But when embedding interfaces, you will have a runtime error incase you try to call the embedded method without having given a value first.
So, the following works fine:
a := Build(x)
// Removing the line below will cause a runtime error when calling a.Foo()
a.Cer = &C{"The CField"}
a.Foo()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论