douken7402 2018-06-29 23:44
浏览 1379

在Go中对多个结构字段进行排序[重复]

This question already has an answer here:

I have an array/slice of members:

type SomeType struct {
    timeStamp time
    typeName string
    other variables...
}

And there are 3 methods on this structure based on typeName, like:

isTypeA(): returns bool
isTypeB(): returns bool
isTypeC(): returns bool

Now this is how my sorting needs to work: - Sort based on timeStamp in ascending order - If the timeStamp is same, then typeA's should come before typeB's which should come before typeC's. (type A, B, C is not really alphabetical)

I am using sort.Slice to sort on timeStamp, but I am not sure how to do the type A,B,C sorting.

</div>
  • 写回答

2条回答 默认 最新

  • dop20345 2018-06-30 01:26
    关注

    Translate the arbitrary type values into something that is sortable in the way your requirements ask.

    func ThingTypeSortable(thing *Thing) int {
        if thing == nil {
            return 0
        }
    
        if thing.isTypeA() {
            return 1
        }
        if thing.isTypeB() {
            return 2
        }
        if thing.isTypeC() {
            return 3
        }
    
        return 0
    }
    

    ...then it's just another thing to sort by if the timestamps are equal.

    sort.Slice(inputs, func(i, j int) bool {
        if inputs[i].t.UTC() != inputs[j].t.UTC() {
            return inputs[i].t.Before(inputs[j].t)
        }
    
        return ThingTypeSortable(inputs[i]) < ThingTypeSortable(inputs[j])
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式