如何在 go 中实现可比较的接口?
How can I implement comparable interface in 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
的问题,因为比较方法将 T
作为参数而不是 Comparable
.
也许我漏掉了一些东西或者没听懂但是可以这样做吗?
您的界面需要一个方法
compare(Comparable) int
但你已经实现了
func (item T) compare(other T) int {
(其他 T 而不是其他 Comparable)
你应该这样做:
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
}
我最近开始学习围棋并面临下一个问题。我想实现 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
的问题,因为比较方法将 T
作为参数而不是 Comparable
.
也许我漏掉了一些东西或者没听懂但是可以这样做吗?
您的界面需要一个方法
compare(Comparable) int
但你已经实现了
func (item T) compare(other T) int {
(其他 T 而不是其他 Comparable)
你应该这样做:
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
}