douqiao4450 2019-03-16 00:38
浏览 148
已采纳

在golang中对切片排序[重复]

This question already has an answer here:

I have a slice in golang which looks something like this.

list := []TripInfo{
        {
            TripID:  "uuid2",
            infov:true
        },
        {
            TripID:  "uuid1",
            infov:false
        },
    }

How can I sort it based on TripID so that it looks something like this?

list := []TripInfo{
        {
            TripID:  "uuid1",
            infov:false
        },
        {
            TripID:  "uuid2",
            infov:true
        },
    }

TripInfo is a struct

type TripInfo struct {
    TripUUID  string
    infov bool
}
</div>
  • 写回答

1条回答 默认 最新

  • dpchen2004 2019-03-16 00:51
    关注

    The sort pkg is your friend:

    import "sort"
    
    // sort slice in place
    sort.Slice(list, func(i, j int) bool {
        return list[i].TripID < list[j].TripID
    })
    

    Playground version.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?