[英]go type conversion - sort 2 slices of different interfaces using shared interface
下面的示例包含2个接口Foo
和Bar
,它们都实现相同的Timestamper
接口。 它还包含了类型ByTimestamp
实现sort.Interface 。
如main
函数所示,我想使用ByTimestamp
类型对Foo
的一部分和Bar
的ByTimestamp
进行排序。 但是,该代码将无法编译,因为它cannot convert foos (type []Foo) to type ByTimestamp
, cannot convert bars (type []Bar) to type ByTimestamp
。
是否可以使用实现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
对不同类型进行排序。 但不是您尝试这样做的方式。 当前的Go规范不允许将一种切片类型转换为另一种切片类型。 您必须转换每个项目。
这是一个使用反射来实现的帮助函数:
// ByTimestamp converts a slice of Timestamper into a slice
// that can be sorted by timestamp.
func ByTimestamp(slice interface{}) sort.Interface {
value := reflect.ValueOf(slice)
length := value.Len()
b := make(byTimestamp, 0, length)
for i := 0; i < length; i++ {
b = append(b, value.Index(i).Interface().(Timestamper))
}
return b
}
在这里查看完整的示例。
而且,如果您只有两种类型,那么改为进行特定于类型的转换可能很有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.