Sobes.tech
Senior

What inheritance options are available in Go and what are their specifics?

sobes.tech AI

Answer from AI

Go does not have classical inheritance like object-oriented languages. Instead, it uses composition and interfaces.

Main features:

  • Composition through embedding: A struct can include another struct as an unnamed field, which allows "inheritance" of methods from the embedded struct.

  • Interfaces: They describe behaviors that can be implemented by different types without explicit inheritance.

Example of composition:

type Animal struct {
    Name string
}

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

// Dog embeds Animal

type Dog struct {
    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())   // overridden method
}

Thus, Go encourages composition and interfaces instead of classical inheritance, which simplifies architecture and increases flexibility.

What inheritance options are available in Go and what… - sobes.tech