Sobes.tech
Junior — Middle

Is it possible to implement inheritance mechanism in Go language?

sobes.tech AI

Answer from AI

Go does not have classical inheritance like object-oriented languages such as Java or C++. Instead, Go uses composition and embedding of structs for code reuse and extending functionality.

For example, you can embed one struct into another, and the methods of the embedded struct become accessible through the outer struct:

package main
import "fmt"

type Animal struct {
    Name string
}

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

type Dog struct {
    Animal // embedding the Animal struct
}

func main() {
    d := Dog{Animal{Name: "Bobby"}}
    d.Speak() // calls the Speak method of the Animal struct
}

Thus, Go achieves behavior similar to inheritance, but it is implemented through composition, which promotes more flexible and simpler design.

Is it possible to implement inheritance mechanism in… - sobes.tech