Inheritance in Go

Although Go is an object-oriented language, it adopts a different philosphy than more object-oritented language such as C# and java. According to Gang of 4 [1], designs should "prefer composition to inheritance". Go uses a concept called embedding [2] to solve inheritance in a way that looks like composition.

Here is an example of inheritance in Golang.

// go run inheritance.go
package main
import "fmt"

type Fruit struct{
    name string
    seeds int
}

func (f Fruit) countForSeeds(){
    fmt.Printf("%s have %d seeds\n", f.name, f.seeds)
}

type Apple struct{
    Fruit
}

func main(){
    var f = Fruit{"Fruit", 2}
    f.countForSeeds()
    var apple = Apple{Fruit{"Apple", 1}}
    apple.countForSeeds()
}

You should see the folllowing output.

Fruit have 2 seeds
Apple have 1 seeds

Notice that we embeded Fruit class into Apple struct as an anoynumous field. Although it does look more like struct composition, especially passing a new Fruit struct object into Apply, we are using the parent method countForSeeds() from a subclass. Unfortunately, there is no way to override the parent methods as all the functions are non-virtual, but you can shadow the method. An example is shownn below:

// go run shadow.go
package main
import "fmt"
type Fruit struct{
    name string
    seeds int
}

func (f Fruit) countForSeeds(){
    fmt.Printf("%s have %d seeds\n", f.name, f.seeds)
}

func (a Apple) countForSeeds(){
    fmt.Printf("%s is an apple with %d seeds\n", a.name, a.seeds)
}

type Apple struct{
    Fruit
}

func main(){
    var f = Fruit{"Fruit", 2}
    f.countForSeeds()
    var apple = Apple{Fruit{"Apple", 1}}
    apple.countForSeeds()
}

You should see the following output:

Fruit have 2 seeds
Apple is an apple with 1 seeds

[1] http://www.amazon.com/dp/0201633612

[2] https://golang.org/ref/spec#Struct_types