Question

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
}
Was it helpful?

Solution

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() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top