cxfans
11/23/2019 - 9:15 AM

sort.Sort

sort.Sort

package main

import (
	"fmt"
	"sort"
)

type StuScore struct {
	name  string
	score int
}

type StuScores []StuScore

func (s StuScores) Len() int {
	return len(s)
}

func (s StuScores) Less(i, j int) bool {
	return s[i].score < s[j].score
}
func (s StuScores) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func main() {
	stus := StuScores{
		{"a", 95},
		{"b", 92},
		{"c", 21},
		{"d", 89},
	}
	sort.Sort(stus)
	for _, v := range stus {
		fmt.Println(v.name, v.score)
	}

	fmt.Println(sort.IsSorted(stus))

	sort.Sort(sort.Reverse(stus))
	for _, v := range stus {
		fmt.Println(v.name, v.score)
	}
}