go使用接口案例排序

一般情况下我们需要对数据进行排序可以使用sort.Ints()方法排序代码

package main

import (
    "fmt"
    "math/rand"
    "sort"
)
func main(){
    var nums []int;
    for i:=0;i<10;i++ {
        num:=rand.Intn(200);
        nums=append(nums,num);
    }
    sort.Ints(nums);
    fmt.Println(nums);
}

但是如果我是结构体切片那么我要如何排序?

package main
import (
    "fmt"
    "math/rand"
    "sort"
)
type Student struct {
    Name string
    Age int
}
type HerosSlice []Student;
//实现Sort排序接口方法
func ( stu HerosSlice ) Len() int{
    return len(stu);
}
func (stu HerosSlice ) Less(i,j int) bool{
    return stu[i].Age > stu[j].Age;
}
func(stu HerosSlice) Swap(i,j int){
    temp:=stu[i];
    stu[i]=stu[j];
    stu[j]=temp;
}
func main(){
    var heros HerosSlice;
    for i:=0;i<10;i++ {
        name:=fmt.Sprintf("英雄名字%d",rand.Intn(100));
        age:= rand.Intn(100);
        stu:=Student{name,age};
        heros=append(heros,stu);
    }
    sort.Sort(heros);
    for _,val:=range heros {
        fmt.Println(val);
    }
}

使用sort包里面sort进行排序

posted on 2020-11-26 22:08  孤灯引路人  阅读(78)  评论(0编辑  收藏  举报

导航