ars
ars

Reputation: 1639

Go embedding: method not inherited

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?

Upvotes: 0

Views: 132

Answers (2)

oren
oren

Reputation: 3209

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
}

Upvotes: 4

Mostafa Solati
Mostafa Solati

Reputation: 1235

You either have to call

c.p.Foo()

or change Child struct to this :

type Child struct {
    *Parent
}

Upvotes: 1

Related Questions