Sorting by Functions
// Importing necessary packages.
package main
import (
"cmp" // Custom comparison package
"fmt"
"slices" // Custom slices package for sorting
)
// The main function, where the execution of the program begins.
func main() {
// Example with a slice of strings
fruits := []string{"peach", "banana", "kiwi"}
// Defining a custom comparison function for sorting based on string length
lenCmp := func(a, b string) int {
return cmp.Compare(len(a), len(b))
}
// Using the SortFunc function from the slices package to sort the string slice using the custom comparison function.
slices.SortFunc(fruits, lenCmp)
// Printing the sorted string slice.
fmt.Println(fruits)
// Example with a slice of custom type (Person)
type Person struct {
name string
age int
}
// Creating a slice of Person instances
people := []Person{
{name: "Jax", age: 37},
{name: "TJ", age: 25},
{name: "Alex", age: 72},
}
// Using the SortFunc function from the slices package to sort the Person slice using a custom comparison function.
slices.SortFunc(people,
func(a, b Person) int {
return cmp.Compare(a.age, b.age)
})
// Printing the sorted Person slice.
fmt.Println(people)
}Output
Last updated