0

I'm giving a try to golang embedding and the following code doesn't compile:

type Parent struct {}

func (p *Parent) Foo() {
}

type Child struct {
    p *Parent
}

func main() {
    var c Child
    c.Foo()
}

with

./tmp2.go:18:3: c.Foo undefined (type Child has no field or method Foo)

What I am doing wrong?

2 Answers 2

4

When you are writing:

type Child struct {
    p *Parent
}

You aren't embedding Parent, you just declare some instance var p of type *Parent.

To call p methods you must forward the call to p

func (c *Child) Foo() {
    c.p.Foo()
}

By embedding you can avoid this bookkeeping, and the syntax will be

type Child struct {
    *Parent
}
Sign up to request clarification or add additional context in comments.

3 Comments

Embedding provides delegation, not inheritance. Think of embedding as inheritance leads to many misconceptions.
@ThunderCat thanks, yeah I know, I wrote it's not like inheritance :) just wanted to give the idea that Child should not embed Parent. it might be the wrong choice of words, I'll edit. Thanks
One can also embed *Parent as OP may have been trying to do in the question. The embedding delegation is not restricted to "public" or exported methods and fields. We don't know the context where OP is using Parent and Child, so it's impossible to know if embedding does or does not make sense for the OP.
1

You either have to call

c.p.Foo()

or change Child struct to this :

type Child struct {
    *Parent
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.