zoukankan      html  css  js  c++  java
  • 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进行排序

  • 相关阅读:
    mvc中压缩html
    简单瀑布流
    MVC4 WebAPI
    css实现隔行换色
    网站变黑白
    reset.css
    选择文本改变浏览器默认的背景色和前景色
    DataBinder.Eval用法范例
    精妙SQL語句
    asp.net面试题收集
  • 原文地址:https://www.cnblogs.com/zh718594493/p/14044905.html
Copyright © 2011-2022 走看看