Sobes.tech
Junior — Middle

Da li je struktura u Go kompatibilna sa interfejsom Comparable?

sobes.tech АИ

Одговор од АИ

U jeziku Go, interfejs Comparable nije deo ugrađenog standarda, ali se često shvata kao interfejs sa metodom za poređenje, na primer:

type Comparable interface {
    Compare(other interface{}) int // vraća -1, 0, 1
}

Struktura u Go je kompatibilna sa interfejsom ako implementira sve metode tog interfejsa. Drugim rečima, ako vaša struktura implementira metodu Compare sa potrebnom potpisom, ona je kompatibilna sa Comparable.

Primer:

type MyStruct struct {
    Value int
}

func (m MyStruct) Compare(other interface{}) int {
    o, ok := other.(MyStruct)
    if !ok {
        return -2 // ili obrada greške
    }
    if m.Value < o.Value {
        return -1
    } else if m.Value > o.Value {
        return 1
    }
    return 0
}

// MyStruct sada implementira Comparable

Ako metoda Compare nije implementirana, struktura nije kompatibilna sa interfejsom Comparable.