Junior — Middle
Czy struktura w Go jest zgodna z interfejsem Comparable?
sobes.tech AI
Odpowiedź od AI
W Go interfejs Comparable nie jest wbudowanym standardem, ale często rozumie się go jako interfejs z metodą porównania, na przykład:
type Comparable interface {
Compare(other interface{}) int // zwraca -1, 0, 1
}
Struktura w Go jest zgodna z interfejsem, jeśli implementuje wszystkie metody tego interfejsu. Innymi słowy, jeśli Twoja struktura implementuje metodę Compare z wymaganą sygnaturą, jest zgodna z Comparable.
Przykład:
type MyStruct struct {
Value int
}
func (m MyStruct) Compare(other interface{}) int {
o, ok := other.(MyStruct)
if !ok {
return -2 // lub obsługa błędu
}
if m.Value < o.Value {
return -1
} else if m.Value > o.Value {
return 1
}
return 0
}
// MyStruct teraz implementuje Comparable
Jeśli metoda Compare nie jest zaimplementowana, struktura nie jest zgodna z interfejsem Comparable.