在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>

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])
})

Use sort.Slice by comparing the fields in sort priority order.

Given variable a of type []SomeType, sort like this:

sort.Slice(a, func(i, j int) bool {
    if !a[i].timeStamp.Equal(a[j].timeStamp) {
        return a[i].timeStamp.Before(a[j].timeStamp)
    }
    if a[i].isTypeA() != a[j].isTypeA() {
        return a[i].isTypeA()
    }
    if a[i].isTypeB() != a[j].isTypeB() {
        return a[i].isTypeB()
    }
    return a[i].isTypeC()
})

This code handles isTypeA(), isTypeB() and isTypeC() as separate fields, even though they are derived from the same underlying field.

I assume you meant to use type time.Time for the timeStamp field. The function uses Time.Equal to correctly compare time.Time values for equality.