How can I implement comparable interface in go?

huangapple go评论78阅读模式
英文:

How can I implement comparable interface in go?

问题

我最近开始学习Go,并遇到了一个问题。我想要实现Comparable接口。我有以下代码:

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

我猜我理解了问题,T没有实现Comparable接口,因为compare方法的参数是T而不是Comparable

也许我漏掉了什么或者理解有误,但是有可能实现这样的功能吗?

英文:

I've recently started studying Go and faced next issue. I want to implement Comparable interface. I have next code:

type Comparable interface {
	compare(Comparable) int
}
type T struct {
	value int
}
func (item T) compare(other T) int {
	if item.value &lt; 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})
}

So I'm getting error

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

And I guess I understand the problem that T doesn't implement Comparable because compare method take as a parameter T but not Comparable.

Maybe I missed something or didn't understand but is it possible to do such thing?

答案1

得分: 6

你的接口要求一个名为compare(Comparable) int的方法,但你实现的是func (item T) compare(other T) int(而不是other Comparable)。

你应该像这样做:

func (item T) compare(other Comparable) int {
    otherT, ok := other.(T) // 通过类型断言获取T的实例。
    if !ok {
        // 处理错误(other不是T类型)
    }
    if item.value < otherT.value {
        return -1
    } else if item.value == otherT.value {
        return 0
    }
    return 1
}

这样你就可以将other断言为T类型,并进行比较操作了。

英文:

Your Interface demands a method

compare(Comparable) int

but you have implemented

func (item T) compare(other T) int { (other T instead of other Comparable)

you should do something like this:

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 &lt; otherT.value {
		return -1
	} else if item.value == otherT.value {
		return 0
	}
	return 1
}

huangapple
  • 本文由 发表于 2016年1月30日 20:26:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/35101768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定