Sobes.tech
Principal

How to use embedding to simulate inheritance in Go?

sobes.tech AI

Answer from AI

In Go, there is no classical inheritance like in object-oriented languages, but you can use embedding to reuse code and imitate inheritance.

Embedding is including one type (usually a struct) inside another without explicitly declaring a field. This allows you to "inherit" methods of the embedded type and use them directly.

Example:

package main

import "fmt"

type Animal struct {
    Name string
}

func (a Animal) Speak() {
    fmt.Println(a.Name, "says")
}

type Dog struct {
    Animal // embedding
    Breed string
}

func main() {
    d := Dog{
        Animal: Animal{Name: "Sharik"},
        Breed:  "German Shepherd",
    }
    d.Speak() // calling Animal's method through Dog
}

Here, Dog embeds Animal, and gains access to its methods directly, which is similar to inheritance. Thus, embedding allows for compositionally extending the functionality of types.