繁体   English   中英

进行类型转换-使用共享接口对2个不同接口的切片进行排序

[英]go type conversion - sort 2 slices of different interfaces using shared interface

下面的示例包含2个接口FooBar ,它们都实现相同的Timestamper接口。 它还包含了类型ByTimestamp实现sort.Interface

main函数所示,我想使用ByTimestamp类型对Foo的一部分和BarByTimestamp进行排序。 但是,该代码将无法编译,因为它cannot convert foos (type []Foo) to type ByTimestampcannot 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM