2016-01-30 9 views
5

मैंने हाल ही में गो का अध्ययन करना शुरू कर दिया है और अगले अंक का सामना करना पड़ा है। मैं तुलनात्मक इंटरफ़ेस को कार्यान्वित करना चाहता हूं। मैं अगले कोड है:मैं तुलनीय इंटरफ़ेस को कैसे कार्यान्वित कर सकता हूं?

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}) 
} 

तो मैं हो रही है त्रुटि

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 

और मुझे लगता है कि मैं इस समस्या को समझते हैं कि TComparable को लागू नहीं करता है की तुलना क्योंकि विधि एक पैरामीटर के रूप ले T लेकिन नहीं Comparable

शायद मुझे कुछ याद आया या समझ में नहीं आया, लेकिन क्या ऐसा करना संभव है?

उत्तर

3

आपका इंटरफ़ेस एक विधि

compare(Comparable) int

की मांग, लेकिन आप

func (item T) compare(other T) int { को लागू किया है (अन्य के बजाय टी अन्य तुलनीय)

आप कुछ इस तरह करना चाहिए:

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

बढ़िया! धन्यवाद! –

+0

आपने दावा के बजाय डबल डायपैच किया होगा –

+0

@Ezequiel मोरेनो क्या आप उदाहरण पोस्ट कर सकते हैं? –

संबंधित मुद्दे

 संबंधित मुद्दे