Interface 可以在结构中嵌入结构以满足接口要求吗

Interface 可以在结构中嵌入结构以满足接口要求吗,interface,struct,go,embedding,Interface,Struct,Go,Embedding,我有以下代码(也可以在中找到)。是否可以实例化一个结构,使其包含一个嵌入式C、S和X。我使用接口的原因是,根据我调用的构建函数,我希望结构具有不同的Bar()实现。我可以有一个S1或S2,其中Bar()稍有不同,但两者都是S'ER package main import "fmt" type Cer interface { Foo() } type Ser interface { Bar() } type Aer interface { Cer Ser }

我有以下代码(也可以在中找到)。是否可以实例化一个结构,使其包含一个嵌入式C、S和X。我使用接口的原因是,根据我调用的构建函数,我希望结构具有不同的Bar()实现。我可以有一个S1或S2,其中Bar()稍有不同,但两者都是S'ER

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 := Build(x)
// Removing the line below will cause a runtime error when calling a.Foo()
a.Cer = &C{"The CField"}
a.Foo() 

如果你想在A中嵌入A,你需要在某个点上使用指针类型(结构不能有自己的值类型作为字段)。对不起。我想嵌入一个C,S和X。我更新了问题。谢谢你的帮助。Build()函数嵌入一个X;我已经学会了如何在围棋中做到这一点。但是,我想知道如何在那里得到C和S。我建立在这里的播放链接上:。您可以看到您的A实例满足接口。dethtron500是的,它确实满足接口。但是在给a.Cer一个值之前,不能调用方法a.Foo()。以类似的方式,这将不起作用:
s:=fmt.Stringer(nil);fmt.Println(s.String())
Hmm。我试图用一个新的(C)在内部构建中这样做,但这不起作用。我在new()和&C{“}之间缺少什么细微差别?参见@alphadogg中的Build(),
new(C)
&C{}
之间没有区别。因此,在Build()中,这应该起作用:
a.Cer=new(C)
@alphadogg中的编译错误是因为在没有先执行类型断言的情况下,无法访问存储在接口中的结构的字段。因此,您的行应该如下所示:
a.Cer.(*C).CField=“set C”
。如果所有Cer都应该有一个CField,那么您应该创建Cer方法,如
SetCField()
等。