Reputation: 1639
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
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
Reputation: 1235
You either have to call
c.p.Foo()
or change Child struct to this :
type Child struct {
*Parent
}
Upvotes: 1