自定義排序接口
package main
//實現(xiàn)排序接口
import (
"fmt"
"math/rand"
"sort"
"strconv"
"time"
)
//用戶機構(gòu)
type User struct {
Name string
Age int
Score float64
}
//切片數(shù)組
type UserSlice []User
func (us UserSlice) Len() int {
//數(shù)組長度
return len(us)
}
func (us UserSlice) Less(i,j int) bool {
//更換條件
return us[i].Score > us[j].Score
}
func (us UserSlice) Swap(i,j int) {
//交換數(shù)組
us[i],us[j] = us[j],us[i]
}
func main() {
var userSlice UserSlice
//設(shè)置隨機因子
rand.Seed(time.Now().UnixNano())
//循環(huán)插入隨機數(shù)據(jù)
for i:=0; i<10; i++{
score ,_:= strconv.ParseFloat(fmt.Sprintf("%.2f",rand.Float64() * 100.00),64)
userSlice = append(userSlice,User{
Age:rand.Intn(80),
Name:fmt.Sprintf("bailong-%d" , i),
Score:score,
})
}
//使用自定義排序
sort.Sort(userSlice)
//輸出排序結(jié)果
for i:=0;i<len(userSlice) ;i++ {
fmt.Println(userSlice[i])
}
}