golang的排序

在写golang的排序时,想用php的array_multisort,理解过array_multisort的快乐之后,正常的排序真的不想写。

然后发现sort包实现了一个interface,只要实现这个interface,想怎么排序就怎么排序。

举个例子就懂了:

package main

import (
	"encoding/json"
	"fmt"
	"sort"
)
type RankList []Rank
type Rank struct {
	Id          int64  `json:"id"`
	Name        string `json:"name"`
	CorrectRate string `json:"correctRate"`
}

func (rankList RankList) Len() int  {
	return len(rankList)
}
//这个方法用来实现随心所欲的排序规则
func (rankList RankList) Less(i, j int) bool  {
	if rankList[i].CorrectRate < rankList[j].CorrectRate {
		return true
	}
	if rankList[i].CorrectRate > rankList[j].CorrectRate {
		return false
	}
	return rankList[i].Id < rankList[j].Id
}
func (rankList RankList) Swap(i, j int) {
	rankList[i], rankList[j] = rankList[j], rankList[i]
}

func main() {
    str := `[{"id":136032810,"name":"\u76c8\u76c82\u73ed","correctRate":"20%"},{"id":136032800,"name":"\u76c8\u76c81\u73ed","correctRate":"20%"},{"id":136032819,"name":"\u76c8\u76c81\u73ed","correctRate":"100%"}
]`
    bStr := []byte(str)
    rankList := new(RankList)
    _ = json.Unmarshal(bStr, rankList)
    fmt.Println(rankList)
    sort.Sort(rankList)
    fmt.Println(rankList)
}

 

你可能感兴趣的:(go)