2016-01-30 12 views
5

Niedawno zacząłem uczyć się Go i stanąłem przed następnym problemem. Chcę zaimplementować porównywalny interfejs. Mam następny kod:Jak mogę wdrożyć porównywalny interfejs w programie Go?

type Comparable interface { 
    compare(Comparable) int 
} 
type T struct { 
    value int 
} 
func (item T) compare(other T) int { 
    if item.value < other.value { 
     return -1 
    } else if item.value == other.value { 
     return 0 
    } 
    return 1 
} 
func doComparison(c1, c2 Comparable) { 
    fmt.Println(c1.compare(c2)) 
} 
func main() { 
    doComparison(T{1}, T{2}) 
} 

Więc Dostaję błędu

cannot use T literal (type T) as type Comparable in argument to doComparison: 
    T does not implement Comparable (wrong type for compare method) 
     have compare(T) int 
     want compare(Comparable) int 

I chyba rozumiem problemu T nie implementuje Comparable ponieważ porównać sposób podjąć jako parametr T ale nie Comparable .

Może coś przeoczyłem lub nie rozumiałem, ale czy można to zrobić?

Odpowiedz

3

interfejsu wymaga metody

compare(Comparable) int

ale wdrożyły

func (item T) compare(other T) int { (inna T zamiast innych porównywalnych)

należy zrobić coś takiego:

func (item T) compare(other Comparable) int { 
    otherT, ok := other.(T) // getting the instance of T via type assertion. 
    if !ok{ 
     //handle error (other was not of type T) 
    } 
    if item.value < otherT.value { 
     return -1 
    } else if item.value == otherT.value { 
     return 0 
    } 
    return 1 
} 
+1

Świetnie! Dziękuję Ci! –

+0

Być może zrobiłeś podwójną diapatch zamiast typu asercja –

+0

@Ezequiel Moreno Czy możesz wysłać przykład, proszę? –

Powiązane problemy