Sobes.tech
Junior — Middle

Kuidas rakendada põhiklassi meetodi väljakutset sisseehitatud komponendist või struktuurist?

sobes.tech AI

Vastus AI-lt

In Go, embedded structures (embedding) allow one type to be included in another, which enables direct use of the embedded type's methods. To call the method of the base (embedded) type, you can access it via the field name.

Example:

package main

import "fmt"

type Base struct{}

func (b Base) Hello() {
    fmt.Println("Hello from Base")
}

type Derived struct {
    Base
}

func (d Derived) Hello() {
    fmt.Println("Hello from Derived")
    // Calling the method of the base type
    d.Base.Hello()
}

func main() {
    d := Derived{}
    d.Hello()
}

In this example, the Hello method of the Derived struct calls the Hello method of the embedded Base struct via d.Base.Hello(). This way, you can explicitly call the base class method from the embedded component.