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)
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM