【发布时间】:2018-08-26 18:27:52
【问题描述】:
下面的示例包含两个接口Foo 和Bar,它们都实现了相同的接口Timestamper。它还包含实现sort.Interface 的类型ByTimestamp。
如函数main 所示,我想使用ByTimestamp 类型对Foos 的切片和Bars 的切片进行排序。但是,代码不会编译,因为它有cannot convert foos (type []Foo) to type ByTimestamp 和cannot convert bars (type []Bar) to type ByTimestamp。
是否可以对实现相同接口的 2 个不同接口切片与实现 sort.Interface 的单一类型进行排序?
package main
import (
"sort"
)
type Timestamper interface {
Timestamp() int64
}
type ByTimestamp []Timestamper
func (b ByTimestamp) Len() int {
return len(b)
}
func (b ByTimestamp) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
func (b ByTimestamp) Less(i, j int) bool {
return b[i].Timestamp() < b[j].Timestamp()
}
type Foo interface {
Timestamper
DoFoo() error
}
type Bar interface {
Timestamper
DoBar() error
}
func getFoos() (foos []Foo) {
// TODO get foos
return
}
func getBars() (bars []Bar) {
// TODO get bars
return
}
func main() {
foos := getFoos()
bars := getBars()
sort.Sort(ByTimestamp(foos))
sort.Sort(ByTimestamp(bars))
}
【问题讨论】:
-
它必须是sort.Interface的实现吗?带有类型断言的 sort.Slice 应该可以工作。
标签: sorting go type-conversion