Sobes.tech
Junior — Middle

How is inheritance mechanism implemented in Go language and what is its implementation?

sobes.tech AI

Answer from AI

In the Go language, there is no classical inheritance like in object-oriented languages. Instead, composition and interfaces are used.

  • Composition: Instead of inheriting structures, you can include one structure within another. This allows "embedding" behavior and data.

  • Interfaces: Go uses interfaces to describe behavior. Any structure that implements the interface's methods is considered its implementation.

Example of composition:

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 structure
}

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

Thus, Go encourages the use of composition and interfaces instead of classical inheritance.