I'm having some issues understanding Go's struct inheritance. I'm trying to do somewhat of an abstraction for an object type. See the example code below:
package main
type Animal struct{}
type Dog struct {
Animal
Color string
}
type Person struct {
Name string
Age int
Pet *Animal
}
func main() {
dog := &Dog{Color: "brown"}
tom := &Person{Name: "Tom", Age: 13, Pet: dog}
}
This is causing a compilation error:
cannot use dog (type *Dog) as type *Animal in field value
What is the correct way to go about doing an abstraction like this? Is it possible in Go?
End goal for the example would be to have different types of Pets - Dog, Cat, Hamser, etc. Then be able to store that into a struct expecting type Animal.
To visualize, something like:
type Person struct {
Name string
Age int
Pet *Dog OR *Cat OR *Hamster
}
Resultsas type[]*DataModelwhere that could be filled with different types of data types, depending on the request.Foothat embeds a struct of typeBarcannot be used in places whereBaris expected. AllFoogets from embeddingBaris access toBar's fields and methods. SoFooIS NOTBar, it only "knows about"Bar, whileBardoes not even know, or care, aboutFooat all.tom := &Person{Name: "Tom", Age: 13, Pet: &dog.Animal}. yourdogvariable contains a fullAnimal, but it is not an animal. It's is own type that consists of its own fields (Colour), and anAnimal, whatever that type might be