基本類型 int 对雪、 float64 和 string 的排序
go 分別提供了 sort.Ints() 、 sort.Float64s() 和 sort.Strings() 函數(shù)
ints := []int{2, 4, 3, 5, 7, 6, 9, 8, 1, 0}
sort.Ints(ints)
fmt.Println(ints) // [0 1 2 3 4 5 6 7 8 9]
如果像要降序,則先需綁定以下3個方法
Paste_Image.png
sort 包下的三個類型 IntSlice 扔字、 Float64Slice 、 StringSlice 分別實現(xiàn)了這三個方法, 對應排序的是 [] int 丢烘、 [] float64 和 [] string, 如果期望逆序排序些椒, 只需要將對應的 Less 函數(shù)簡單修改一下即可
ints := []int{2, 4, 3, 5, 7, 6, 9, 8, 1, 0}
sort.Sort(sort.Reverse(sort.IntSlice(ints)))
fmt.Println(ints) // [9 8 7 6 5 4 3 2 1 0]
<h3>結構體類型的排序</h3>
type Person struct {
Age int32
}
type Persons []*Person
func (this Persons) Len() int {
return len(this)
}
func (this Persons) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}
func (this Persons) Less(i, j int) bool {
return this[i].Age > this[j].Age
}
func SortStruct() {
p1 := &Person{1}
p2 := &Person{4}
p3 := &Person{2}
list := make([]*Person, 0)
list = append(list, p1, p2, p3) //需要排序的數(shù)組
persons := Persons{}
persons = list
sort.Sort(persons) //通過重寫的 less播瞳,用age 屬性進行排序
for _, v := range persons {
fmt.Println(v.Age)
}
}