Sorting slices is a commonly used function in Golang and can be quickly implemented using the sort.Slice function. This function allows sorting slices by passing in a custom comparison function.
The sort.Slice function is defined as follows:
func Slice(slice interface{}, less func(i, j int) bool)
Among them, the slice parameter specifies the slice to be sorted, and the less parameter is a comparison function used to define the comparison rules of slice elements.
The following is a sample code that demonstrates how to use the sort.Slice function to sort slices:
package main import ( "fmt" "sort" ) type Person struct { Name string Age int } type Persons []Person func (p Persons) Len() int { return len(p) } func (p Persons) Less(i, j int) bool { return p[i].Age < p[j].Age } func (p Persons) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func main() { persons := Persons{ {"Alice", 25}, {"Bob", 30}, {"Charlie", 20}, {"David", 35}, } fmt.Println("Before sort:", persons) sort.Slice(persons, func(i, j int) bool { return persons[i].Age < persons[j].Age }) fmt.Println("After sort:", persons) }
In the above code, we define a Person structure and a Persons slice type. The Persons type implements three interfaces in the sort package: Len, Less, and Swap, thus indicating that Persons can be sorted.
In the main function, we define a persons slice instance and use the sort.Slice function to sort the slice in the following code. In this case, we define a way to sort in ascending order by the Person.Age field by passing an anonymous function as the less parameter.
Finally, we output the sorted results and you can see that the sorting has been completed.
Summary:
The sort.Slice function is a shortcut for slice sorting in Golang. We can define different collations by passing different comparison functions. When passing the comparison function in sort.Slice, we can use an anonymous function or a structure that implements the sort interface.
The above is the detailed content of How to sort slices using sort.Slice function in golang. For more information, please follow other related articles on the PHP Chinese website!