Sobes.tech
Junior — Middle

Can you explain the inheritance principle and how it is implemented in Go?

sobes.tech AI

Answer from AI

In the Go language, there is no traditional inheritance like in other object-oriented languages. Instead, Go uses composition and embedding to reuse code and extend functionality.

Embedding allows including one type (struct) into another, and the methods of the embedded type become accessible to the outer type, similar to inheritance.

Example:

type Animal struct {
    Name string
}

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

// Embedding Animal into Dog

type Dog struct {
    Animal
}

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

func main() {
    dog := Dog{Animal{Name: "Buddy"}}
    fmt.Println(dog.Name)       // Access to Animal field
    fmt.Println(dog.Speak())    // Overridden method
}

Thus, Go achieves a similar effect to inheritance through composition and embedding, avoiding the complexities of classical hierarchy.