I understood that Go has no inheritance and works with composition.
Here is my small example:
type Car struct {
XMLName xml.Name `xml:"response"`
// some properties coming from a XML file
}
type Audi struct {
Car
// some more properties coming from a XML file
}
func UnmarshalFromXML(url string, car *Car) { /* fill the properties from the XML file */ }
What I actually want:
var audi Audi
UnmarshalFromXML("someURL", &audi)
But this does not work, because there is no inheritance. But I need structs to use the unmarshal functionality for XML files.
So what to do?
You could try using interfaces instead
type Car interface {
theCar()
}
type CarBase struct {
}
func (_ CarBase) theCar() {
}
type Audi struct {
CarBase
}
func UnmarshalFromXML(url string, car Car)
Inheritance in go
very different from another languages. When a type extended from a parent type, the two types remain distinct. The solution in your case is to create an interface, and pass interface as parameter in the function. Take a look to the example below:
package main
import (
"fmt"
)
// creating an interface
type Vehicle interface {
Move()
}
type Car struct {
Color string
Brand string
}
// Car has method Move(), automatically stated implement Vehicle interface
func (c *Car) Move() {
fmt.Print("Car is moving")
}
func(c *Car) Honk() {
fmt.Print("Teeeet... Teet")
}
type Audi struct {
EngineType string
Car
}
// passing an interface
func UnmarshalFromXML(url string, v Vehicle) {
fmt.Print(v)
v.Honk()
}
func main() {
var car = Car{Color:"Green"}
var audi = Audi{}
audi.Car = car
audi.Brand = "Audi"
audi.EngineType = "EC"
UnmarshalFromXML("someURL", &audi)
}
https://play.golang.org/p/ZO4P_3fjmz
This article have a great explanation of OOP in go
: http://spf13.com/post/is-go-object-oriented/