Junior
Kaip patikrinti sąsajos tipą Go?
sobes.tech AI
Atsakymas iš AI
Go kalboje dažnai naudojami type assertion arba type switch patikrinti interfeiso tipą.
Jei turite kintamąjį, kurio tipas yra interfeisas, pavyzdžiui, var i interface{}, ir norite patikrinti, ar jis įgyvendina konkretų interfeisą arba yra tam tikro tipo, galite tai padaryti taip:
if v, ok := i.(MyInterface); ok {
// i įgyvendina MyInterface, v yra konvertuotas tipas
}
Patikrinimui kelių tipų patogiau naudoti type switch:
switch v := i.(type) {
case MyInterface:
// i įgyvendina MyInterface
case *MyStruct:
// i yra nuoroda į MyStruct
default:
// kitas tipas
}
Jei norite patikrinti tipą dinamiškiau, galite naudoti paketą reflect:
import "reflect"
t := reflect.TypeOf(i)
if t.Implements(reflect.TypeOf((*MyInterface)(nil)).Elem()) {
// i įgyvendina MyInterface
}
Taip, paprastais atvejais, pakanka type assertion arba type switch; sudėtingesniais atvejais — reflection.