golang对struct排序的方法

方法一:使用 sort.Slice() 进行排序

package main

import (
   "fmt"
   "sort"
)

type myStruct struct {
   name string
   score int
}

func main()  {
   s1 := []myStruct{
      {name: "mcc", score: 1},
      {name: "get", score: 2},
      {name: "zp", score: 0},
   }
   fmt.Println("排序前:", s1)
   sort.Slice(s1, func(i, j int) bool {
      return s1[i].score < s1[j].score
   })
   fmt.Println("排序后:", s1)
}

方法二、使用sort.Sort() 进行排序

使用sort.Sort() 方法需要重写Len()、Swap()、Less() 这三个方法

package main

import (
   "fmt"
   "sort"
)

type myStruct struct {
   name string
   score int
}

type m2 []myStruct

func (a m2) Len() int {
   return len(a)
}

func (a m2) Swap(i, j int) {
   a[i], a[j] = a[j], a[i]
}

func (a m2) Less(i, j int) bool {
   return a[i].score > a[j].score
}

func main()  {
   s2 := []myStruct{
      {name: "mcc", score: 1},
      {name: "get", score: 2},
      {name: "zp", score: 0},
   }
   fmt.Println("排序前:", s2)
   sort.Sort(m2(s2))
   fmt.Println("排序后:", s2)
}
posted @ 2022-02-10 12:47  GetcharZp  阅读(1242)  评论(0编辑  收藏  举报