dimanche 20 août 2023

What is the point of implementing an interface in go?

This code bellow gives runtime error: invalid memory address or nil pointer dereference, curious why enters the if clause and what is the point of implementing an interface in go if that if verifies for having the function without "implementing". The Module keyword within the Media creates the property Module within itself, that seems to act as a property of struct but also inherits its functions.

package main

type Module interface {
    Init()
}

type Media struct {
    Module // <- Why?
}

// func (m *Media) Init() {}

func main() {

    var v any = &Media{}

    if module, isModule := v.(Module); isModule {
        module.Init()
    }
}

Aucun commentaire:

Enregistrer un commentaire