Golang slices.SortFunc Function

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

  1. Introduction
  2. slices.SortFunc Function Syntax
  3. Examples
    • Basic Usage
    • Sorting a Slice of Structs
    • Custom Sorting for Complex Types
  4. Real-World Use Case Example
  5. 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 a should come before b.
    • Zero if a and b are considered equal.
    • A positive number if a should come after b.

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 x in place according to the custom comparison logic defined by the cmp function.

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.SortFunc function sorts the numbers slice in descending order using the custom comparison function compareDescending.

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.SortFunc function sorts the people slice by the Age field in ascending order using the custom comparison function compareByAge.

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.SortFunc function sorts the products slice first by Rating and then by Price using the custom comparison function compareByRatingAndPrice.

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.SortFunc function sorts the employees slice by Department and, within each department, by Salary using the custom comparison function compareByDeptAndSalary.

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top