Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How golag uses sort.slice packages to implement object list sorting

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how golag uses the sort.slice package to achieve object list sorting. Xiaobian thinks it is quite practical, so share it with you as a reference. I hope you can gain something after reading this article.

1. Sort.Sort Introduction

Sort with sort.Slice, because slice abstracts struct, and slice is encapsulated, simple basic types can use sort, use sort sort to rewrite three interfaces, do not want to learn sort sort can directly see step 3

Here we will compare the use of sort and slice

1.1 Analyzing built-in sort packages

1.2 Analysis sort.go

要想实现自定义对象的排序功能,需要重写这三个interface

外部调用sort方法即可实现排序

func Sort(data Interface) {n := data.Len()quickSort(data, 0, n, maxDepth(n))}

通过sort源码可以看到用的快速排序,不懂快排的可以自行重温快排算法,这里就不讲解快排原理了

2.使用方法2.1基础类型排序

基础类型的排序直接在sort.go去找就行了

package mainimport ("fmt""sort")func main() {intList := [] int {2, 4, 3, 5, 7, 6, 9, 8, 1, 0}float8List := [] float64 {4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}stringList := [] string {"a", "c", "b", "d", "f", "i", "z", "x", "w", "y"}sort.Ints(intList)sort.Float64s(float8List)sort.Strings(stringList)fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList)}

2.2对象排序(单一字段)

如果对一个struct对象的某一个字段进行排序就需要重写一组len,less,swap接口,如果有多组就需要重写多组接口。

下面直接看例子:

如果一个对象只有一个字段需要排序就用下面的例子比较简单

package mainimport ("fmt""sort")type Person struct {Name stringAge int}// 按照 Person.Age 从大到小排序type PersonSlice [] Personfunc (a PersonSlice) Len() int { // 重写 Len() 方法return len(a)}func (a PersonSlice) Swap(i, j int){ // 重写 Swap() 方法a[i], a[j] = a[j], a[i]}func (a PersonSlice) Less(i, j int) bool { // 重写 Less() 方法, 从大到小排序return a[j].Age < a[i].Age}func main() {people := [] Person{{"zhang san", 12},{"li si", 30},{"wang wu", 52},{"zhao liu", 26},}fmt.Println(people)sort.Sort(PersonSlice(people)) // 按照 Age 的逆序排序fmt.Println(people)sort.Sort(sort.Reverse(PersonSlice(people))) // 按照 Age 的升序排序fmt.Println(people)}2.3对象排序(多字段)

多个了SortBy方法可以确定是升序还是降序,同时可以确定排序字段是哪个

package mainimport ("fmt""sort")type Person struct {Name stringAge int}type PersonWrapper struct {people [] Personby func(p, q * Person) bool}//用来判断升序还是降序type SortBy func(p, q *Person) boolfunc (pw PersonWrapper) Len() int { // 重写 Len() 方法return len(pw.people)}func (pw PersonWrapper) Swap(i, j int){ // 重写 Swap() 方法pw.people[i], pw.people[j] = pw.people[j], pw.people[i]}func (pw PersonWrapper) Less(i, j int) bool { // 重写 Less() 方法return pw.by(&pw.people[i], &pw.people[j])}// 封装成 SortPerson 方法func SortPerson(people [] Person, by SortBy){sort.Sort(PersonWrapper{people, by})}func main() {people := [] Person{{"zhang san", 12},{"li si", 30},{"wang wu", 52},{"zhao liu", 26},}fmt.Println(people)//推荐用封装的SortPerson方法sort.Sort(PersonWrapper{people, func (p, q *Person) bool {return q.Age < p.Age // Age 递减排序}})fmt.Println(people)//推荐用这种SortPerson(people, func (p, q *Person) bool {return p.Name < q.Name // Name 递增排序})fmt.Println(people)}

如果不喜欢用sortby方法,也可以重写多个less、len、swap方法,

下面的方法就调用起来比较简单,不用重写by跟sortby方法,但是上面的比较灵活(理解可能比下面的费劲)

package mainimport ("fmt""sort")type Person struct {Name stringWeight int}type PersonSlice []Personfunc (s PersonSlice) Len() int { return len(s) }func (s PersonSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }type ByName struct{ PersonSlice } // 将 PersonSlice 包装起来到 ByName 中func (s ByName) Less(i, j int) bool { return s.PersonSlice[i].Name < s.PersonSlice[j].Name } // 将 Less 绑定到 ByName 上type ByWeight struct{ PersonSlice } // 将 PersonSlice 包装起来到 ByWeight 中func (s ByWeight) Less(i, j int) bool { return s.PersonSlice[i].Weight < s.PersonSlice[j].Weight } // 将 Less 绑定到 ByWeight 上func main() {s := []Person{{"apple", 12},{"pear", 20},{"banana", 50},{"orange", 87},{"hello", 34},{"world", 43},}sort.Sort(ByWeight{s})fmt.Println("People by weight:")printPeople(s)sort.Sort(ByName{s})fmt.Println("\nPeople by name:")printPeople(s)}func printPeople(s []Person) {for _, o := range s {fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)}}3.sort.Slice介绍3.1使用方法

很明显将对象抽象成interface,而上面对对象的排序,只能是person这种特定对象

调用的时候有点类似java的重写compare方法

package mainimport ("fmt""sort")type Person struct {Name stringWeight int}func main() {s := []Person{{"apple", 12},{"pear", 20},{"banana", 50},{"orange", 87},{"hello", 34},{"world", 43},}//可以向上面一样对排序字段封装,加一个sortby字段传递sort.Slice(s,func(i,j int)bool{return s[i].Weight < s[j].Weight})fmt.Println("People by weight:")printPeople(s)sort.Slice(s,func(i,j int)bool{return s[i].Name < s[j].Name})fmt.Println("\nPeople by name:")printPeople(s)}func printPeople(s []Person) {for _, o := range s {fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)}}3.2运行

关于"golag如何使用sort.slice包实现对象list排序"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report