Go provides a sort
package that provides functions for sorting slices of various data types, including integers, strings, and custom types. Here’s an example of using the sort
package to sort a slice of integers:
package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{7, 4, 8, 2, 9, 1}
sort.Ints(numbers)
fmt.Println(numbers)
}
In this example, the sort.Ints
function sorts the slice of integers in ascending order. The sorted slice is then printed to the console.
You can also sort slices of custom types by defining the Less
method for the type. The Less
method should return true
if the first element is less than the second element, and false
otherwise. Here’s an example of sorting a slice of custom types:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%s: %d", p.Name, p.Age)
}
type ByAge []Person
func (a ByAge) Len() int {
return len(a)
}
func (a ByAge) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByAge) Less(i, j int) bool {
return a[i].Age < a[j].Age
}
func main() {
people := []Person{
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
}
sort.Sort(ByAge(people))
fmt.Println(people)
}
In this example, the ByAge
type is a slice of Person
structs and implements the sort.Interface
type. The Len
, Swap
, and Less
methods are defined for the ByAge
type, allowing it to be sorted using the sort.Sort
function. The ByAge
type is sorted in ascending order by age, and the sorted slice is then printed to the console.
Leave a Reply