Sobes.tech
Junior — Middle

Kuidas realiseeritakse pärimise mehhanism Go keeles ja milline on selle rakendamine?

sobes.tech AI

Vastus AI-lt

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 into another. This allows "embedding" behavior and data.

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

Example of composition:

package main

import "fmt"

type Animal struct {
    Name string
}

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

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

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

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