In IT development, sometimes we need to sort structure arrays. The Go language provides sort package, the most commonly used one is the () function. But how do we achieve this when we need to keep the order between the same elements stable?
This article will introduce to you how to use () to stabilize a certain field of a structure array. At the same time, we will show you how to use reflection and structure labels to make the sorting more elegant and universal.
Tie the "Sort Tag" on the structure field
If we have a nameStudent
The structure ofName
String fields, we want to sort the Student array by Name field, what should we do? We can place a "Sort tag" for the Name field, indicating the order used when sorting:
type Student struct { Id int sort:"id" Name string sort:"name" Score float64 sort:"score" }
Use () for stable sorting
Next, we will show a sorting function that can be applied to any type. This function will get the sorted fields of the structure by reflection and labels and sort them using ().
func SortSliceStable(slice interface{}, sortField string) { rv := (slice) if () != { panic("SortSliceStable called with non-slice type") } if () == 0 { return } // Get the element type of the structure elemType := ().Elem() // Get sorting fields field, ok := (sortField) if !ok { panic("SortSliceStable called with unknown or unexported struct field name: " + sortField) } // Get less function less := func(i, j int) bool { v1 := (i).FieldByName() v2 := (j).FieldByName() switch () { case , reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return () < () case reflect.Float32, reflect.Float64: return () < () case : return () < () } panic("unsupported type") } // Use(slice, less) }
Now we can sort using this sort function as follows:
func main() { students := []Student{ {1, "zhangsan", 90.0}, {2, "lisi", 80.0}, {3, "wangwu", 70.0}, } // Sort by Name field SortSliceStable(students, "name") (students) }
Run the above code to get the results of stable sorting by the Name field:
[{2 lisi 80} {3 wangwu 70} {1 zhangsan 90}]
By adding labels and using reflection, we make the sorting process more universal and elegant. This method can effectively improve our work efficiency and code quality, and is worthy of our promotion and application. Stable sorting, it turns out that simple!
This is the end of this article about the detailed explanation of stable sorting of Go advanced features. For more relevant Go sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!