Sobes.tech
Junior — Middle

Kako odrediti da li određena struktura implementira zadati interfejs?

sobes.tech АИ

Одговор од АИ

U Go jeziku, implementacija interfejsa se proverava neizravno: ako tip sadrži sve metode deklarisane u interfejsu, on automatski implementira taj interfejs.

Da biste odredili da li struktura implementira dati interfejs, možete:

  1. Pokušajte da dodelite instancu strukture promenljivoj tipa interfejs — ako kompilacija uspe, to znači da struktura implementira interfejs.
  2. Koristite statičku proveru pomoću _var _:
var _ MyInterface = (*MyStruct)(nil)

Ako se ovaj kod kompajlira bez grešaka, to znači da MyStruct implementira interfejs MyInterface.

Primer:

type MyInterface interface {
    DoSomething()
}

type MyStruct struct {}

func (m *MyStruct) DoSomething() {
    // implementacija
}

// Provera implementacije interfejsa
var _ MyInterface = (*MyStruct)(nil)

Na ovaj način, u Go jeziku nije potrebno eksplicitno navesti implementaciju interfejsa — dovoljno je implementirati sve njegove metode.