Sobes.tech
Middle

How can embedded structures in Go be used to simulate inheritance? What does it provide and what is it used for?

sobes.tech AI

Answer from AI

In Go, there is no classical inheritance like in object-oriented languages, but embedded structures (embedding) allow for its imitation.

When one struct includes another as an unnamed field, the methods of the embedded struct become accessible to the outer struct, similar to inheritance.

This provides:

  • Code reuse
  • Composition instead of inheritance
  • The ability to extend the behavior of the embedded struct

Example:

type Animal struct {
    Name string
}

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

// Embedding Animal in Dog
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())   // call to overridden method
}

It is used to create more complex types based on simple ones, without a rigid class hierarchy.

How can embedded structures in Go be used to simulate… - sobes.tech