英文:
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 < 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 < otherT.value {
return -1
} else if item.value == otherT.value {
return 0
}
return 1
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论