package main import ( "fmt" "sort" ) func main() { nums := []int{4, 3, 1, 5, 2} sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] }) fmt.Println(nums) // Output: [1 2 3 4 5] }
package main import ( "fmt" "sort" ) type Person struct { Name string Age int } type ByAge []Person func(p ByAge) Len() int { return len(p) } func(p ByAge) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func(p ByAge) Less(i, j int) bool { return p[i].Age < p[j].Age } func main() { people := []Person{ {"Alice", 25}, {"Bob", 27}, {"Charlie", 22}, } sort.Sort(ByAge(people)) fmt.Println(people) // Output: [{Charlie 22} {Alice 25} {Bob 27}] }In this example, we declare a new type ByAge that implements the sort.Interface. The Less method compares the Age field of two Person structs to determine the sorting order. We then pass a ByAge instance to the sort.Sort function to sort the people slice by age. Package: The sort interface is part of the "sort" package in Go.