golang 對自定義類型排序


package main import ( "fmt" "sort" ) type Person struct { Name string Age int } type Persons []Person // Len()方法和Swap()方法不用變化 // 獲取此 slice 的長度 func (p Persons) Len() int { return len(p) } // 交換數據 func (p Persons) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // 嵌套結構體 將繼承 Person 的所有屬性和方法 // 所以相當於SortByName 也實現了 Len() 和 Swap() 方法 type SortByName struct{ Persons } // 根據元素的姓名長度降序排序 (此處按照自己的業務邏輯寫) func (p SortByName) Less(i, j int) bool { return len(p.Persons[i].Name) > len(p.Persons[j].Name) } type SortByAge struct{ Persons } // 根據元素的年齡降序排序 (此處按照自己的業務邏輯寫) func (p SortByAge) Less(i, j int) bool { return p.Persons[i].Age > p.Persons[j].Age } func main() { persons := Persons{ { Name: "test123", Age: 20, }, { Name: "test1", Age: 22, }, { Name: "test12", Age: 21, }, } fmt.Println("排序前") for _, person := range persons { fmt.Println(person.Name, ":", person.Age) } sort.Sort(SortByName{persons}) fmt.Println("排序后") for _, person := range persons { fmt.Println(person.Name, ":", person.Age) } }


免責聲明!

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



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