gpt4 book ai didi

go - 如何在 go 中实现可比较的接口(interface)?

转载 作者:IT王子 更新时间:2023-10-29 01:27:34 34 4
gpt4 key购买 nike

<分区>

我最近开始学习 Go 并面临下一个问题。我想实现 Comparable 接口(interface)。我有下一个代码:

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 的问题,因为比较方法将 T 作为参数而不是 可比较

也许我遗漏了什么或不明白,但有可能做这样的事情吗?

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com