可以在结构中嵌入结构以满足界面

时间:2014-05-06 03:35:24

标签: interface struct go embedding

我有以下代码(也可在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
}

1 个答案:

答案 0 :(得分:1)

简短回答是:是的,你可以。

但是在嵌入接口时,如果没有首先给出值,则尝试调用嵌入式方法时会出现运行时错误。

因此,以下工作正常:

a := Build(x)
// Removing the line below will cause a runtime error when calling a.Foo()
a.Cer = &C{"The CField"}
a.Foo()