The slices.SortFunc function in Golang is part of the slices package, introduced in Go 1.21 as part of the standard library. This function allows you to sort the elements of a slice in place based on a custom comparison function. It is particularly useful when you need to sort a slice according to criteria that are not covered by the default ordering.
Table of Contents
- Introduction
slices.SortFuncFunction Syntax- Examples
- Basic Usage
- Sorting a Slice of Structs
- Custom Sorting for Complex Types
- Real-World Use Case Example
- Conclusion
Introduction
The slices.SortFunc function provides a flexible way to sort elements in a slice based on custom criteria. This function allows you to define your own comparison logic, making it ideal for sorting complex types or applying non-standard sorting rules. By using slices.SortFunc, you can order your data according to specific needs.
slices.SortFunc Function Syntax
The syntax for the slices.SortFunc function is as follows:
func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int)
Parameters:
x S: The slice to be sorted.cmp func(a, b E) int: A custom comparison function that defines the sorting order. It should return:- A negative number if
ashould come beforeb. - Zero if
aandbare considered equal. - A positive number if
ashould come afterb.
- A negative number if
Returns:
void: This function does not return a value; it modifies the slice in place.
Behavior:
- In-place custom sorting: The function sorts the elements in the slice
xin place according to the custom comparison logic defined by thecmpfunction.
Examples
Basic Usage
This example demonstrates how to use slices.SortFunc to sort a slice of integers in descending order.
Example
package main
import (
"fmt"
"slices"
)
func main() {
// Define a slice of integers
numbers := []int{5, 3, 4, 1, 2}
// Define a custom comparison function for descending order
compareDescending := func(a, b int) int {
return b - a
}
// Sort the slice in descending order
slices.SortFunc(numbers, compareDescending)
// Print the sorted slice
fmt.Println("Sorted slice in descending order:", numbers)
}
Output:
Sorted slice in descending order: [5 4 3 2 1]
Explanation:
- The
slices.SortFuncfunction sorts thenumbersslice in descending order using the custom comparison functioncompareDescending.
Sorting a Slice of Structs
This example shows how to use slices.SortFunc to sort a slice of structs by a specific field, such as Age.
Example
package main
import (
"fmt"
"slices"
)
type Person struct {
Name string
Age int
}
func main() {
// Define a slice of Person structs
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
// Define a custom comparison function to sort by Age
compareByAge := func(a, b Person) int {
return a.Age - b.Age
}
// Sort the slice by Age in ascending order
slices.SortFunc(people, compareByAge)
// Print the sorted slice
for _, person := range people {
fmt.Printf("%s: %d\n", person.Name, person.Age)
}
}
Output:
Bob: 25
Alice: 30
Charlie: 35
Explanation:
- The
slices.SortFuncfunction sorts thepeopleslice by theAgefield in ascending order using the custom comparison functioncompareByAge.
Custom Sorting for Complex Types
This example demonstrates how slices.SortFunc can be used to sort a slice of complex types based on multiple fields.
Example
package main
import (
"fmt"
"slices"
)
type Product struct {
Name string
Price float64
Rating float64
}
func main() {
// Define a slice of Product structs
products := []Product{
{"Laptop", 1000.0, 4.5},
{"Phone", 800.0, 4.7},
{"Tablet", 600.0, 4.3},
}
// Define a custom comparison function to sort by Rating, then by Price
compareByRatingAndPrice := func(a, b Product) int {
if a.Rating != b.Rating {
if a.Rating > b.Rating {
return 1
}
return -1
}
if a.Price > b.Price {
return 1
}
if a.Price < b.Price {
return -1
}
return 0
}
// Sort the slice by Rating, then by Price in ascending order
slices.SortFunc(products, compareByRatingAndPrice)
// Print the sorted slice
for _, product := range products {
fmt.Printf("%s: Price: %.2f, Rating: %.1f\n", product.Name, product.Price, product.Rating)
}
}
Output:
Tablet: Price: 600.00, Rating: 4.3
Laptop: Price: 1000.00, Rating: 4.5
Phone: Price: 800.00, Rating: 4.7
Explanation:
- The
slices.SortFuncfunction sorts theproductsslice first byRatingand then byPriceusing the custom comparison functioncompareByRatingAndPrice.
Real-World Use Case Example: Sorting Employee Records by Multiple Criteria
A practical use case for slices.SortFunc is sorting employee records by multiple criteria, such as Department and Salary.
Example: Sorting Employee Records
package main
import (
"fmt"
"slices"
)
type Employee struct {
Name string
Department string
Salary float64
}
func main() {
// Define a slice of Employee structs
employees := []Employee{
{"Alice", "Engineering", 75000},
{"Bob", "Sales", 55000},
{"Charlie", "Engineering", 90000},
{"Dave", "Sales", 60000},
}
// Define a custom comparison function to sort by Department, then by Salary
compareByDeptAndSalary := func(a, b Employee) int {
if a.Department != b.Department {
if a.Department > b.Department {
return 1
}
return -1
}
if a.Salary > b.Salary {
return 1
}
if a.Salary < b.Salary {
return -1
}
return 0
}
// Sort the slice by Department, then by Salary in ascending order
slices.SortFunc(employees, compareByDeptAndSalary)
// Print the sorted slice
for _, employee := range employees {
fmt.Printf("%s: Department: %s, Salary: %.2f\n", employee.Name, employee.Department, employee.Salary)
}
}
Output:
Charlie: Department: Engineering, Salary: 90000.00
Alice: Department: Engineering, Salary: 75000.00
Dave: Department: Sales, Salary: 60000.00
Bob: Department: Sales, Salary: 55000.00
Explanation:
- The
slices.SortFuncfunction sorts theemployeesslice byDepartmentand, within each department, bySalaryusing the custom comparison functioncompareByDeptAndSalary.
Conclusion
The slices.SortFunc function in Go is used for sorting slices based on custom comparison logic. It allows for flexible and precise ordering of elements, making it ideal for complex sorting tasks that go beyond simple numeric or lexicographic ordering. By using slices.SortFunc, you can ensure that your data is organized according to the specific criteria required by your Go applications.