Sobes.tech
Middle

How can embedded structures be used 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 embedded structures to simulate inheritance. This is achieved by including one structure within another without specifying a field name, which allows you to "inherit" methods of the embedded structure.

Example:

package main
import "fmt"

type Animal struct {
    Name string
}

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

type Dog struct {
    Animal // embedded structure
    Breed string
}

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

Thus, Dog "inherits" the methods of Animal and can use them directly.

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