Reputation: 21
A bit confused on this one. Please see playground.
I would expect go to allow you to call a method that takes a parent with a child that embeds that parent.
package main
import (
"fmt"
)
type Parent struct {
A string
}
type Child struct {
Parent
}
func SomeFunction(parent Parent) {
fmt.Println("%v", parent.A)
}
func main() {
child := Child{Parent{A:"test"}}
SomeFunction(child) //prog.go:21: cannot use child (type Child) as type Parent in argument to SomeFunction
}
If I call this with "child.Parent" it works but in that case I can't use any code within the function that utilizes the value as an empty interface. Googled the heck out of this and found one very interesting and helpful page. Golang concepts from an OOP point of view. Any guidance on what i'm missing here is welcome. Perhaps this is just me not fully "getting" Golang here.
Upvotes: 1
Views: 2197
Reputation: 25169
Go does not support inheritance, so the concept of parents and children do not exist. This makes the names confusing in the text below. It also indicates that you need to make the mental leap between reimplementing inheritance, to designing data structures in a go-like manner. This very issue took me some time to get my head around, and the answer was 'don't start with an inheritance hierarchy and wonder how to do it in go, start with go and design what you want to do with the tools available'.
SomeFunction
is defined to take a Parent
as a parameter, so you must pass it a parent. If you want to pass it a child, you need to do this, i.e. use:
SomeFunction(child.Parent)
That's what you do to pass an embedded struct.
However, what I suspect you really want to do is declare an interface called Parent
, have Child
implement it, and have SomeFunction
take a Parent
interface. Your confusion is then going to be that currently Parent
has a data member, and interfaces have only functions. The neatest way to fix that depends on what you are trying to do, but one route would be to provide another function to return the data member. All the 'child' classes could then embed this data member and a the function could return it (or a pointer to it). However, without a clearer idea of what you are trying to do, this is only speculation.
Upvotes: 4