Sobes.tech
Principal

Does Go have inheritance or composition?

sobes.tech AI

Answer from AI

Go lacks traditional inheritance like in C# or Java. Instead, Go uses composition and interfaces for code reuse and polymorphism.

Composition in Go is achieved by embedding one type into another. This allows "embedding" behavior and data from another type without inheritance.

Example of composition:

type Animal struct {
    Name string
}

func (a Animal) Speak() string {
    return "..."
}

type Dog struct {
    Animal // embedding Animal
}

func (d Dog) Speak() string {
    return "Woof!"
}

func main() {
    d := Dog{Animal{Name: "Buddy"}}
    fmt.Println(d.Name)    // access to Animal field
    fmt.Println(d.Speak()) // call overridden method
}

Thus, Go prefers composition over inheritance, which simplifies architecture and reduces coupling.