【发布时间】:2014-05-06 03:35:24
【问题描述】:
我有以下代码(也可在Go Playground 中找到)。是否可以实例化一个 A 结构,使其包含嵌入式 C、S 和 X。我使用接口的原因是,根据我调用的 Build 函数,我希望结构具有不同的实现酒吧()。我可以有一个 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
}
【问题讨论】:
-
如果你想在 A 中嵌入一个 A,你需要在某个时候使用一个指针类型(一个结构不能有它自己的值类型作为一个字段)。
-
对不起。我想嵌入 C、S 和 X。我更新了问题。谢谢你的收获。 Build() 函数嵌入了一个 X;我已经学会了如何在 Go 中做到这一点。但是,我想知道如何在其中获得 C 和 S。
标签: interface struct go embedding