2016-01-30 14 views
5

Ho recentemente iniziato a studiare Go e ho dovuto affrontare il prossimo numero. Voglio implementare un'interfaccia comparabile. Ho codice seguente:Come posso implementare un'interfaccia comparabile in 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}) 
} 

Così sto ottenendo errore

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 

E credo di capire il problema che T non implementa Comparable perché confrontare metodo prende come parametro T ma non Comparable .

Forse mi sono perso qualcosa o non ho capito, ma è possibile fare una cosa del genere?

risposta

3

Your Interface richiede un metodo

compare(Comparable) int

ma è stato implementato

func (item T) compare(other T) int { (altri T al posto di altri comparabili)

si dovrebbe fare qualcosa di simile:

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

Ottimo! Grazie! –

+0

Si potrebbe aver fatto doppio diapatch invece di tipo asserzione –

+0

@Ezequiel Moreno Potresti postare un esempio per favore? –

Problemi correlati