Golang Sorting Slices
Sorting Slices
In Go, sorting a slice is often necessary when working with data that needs to be organized or structured for better usability, efficiency, or presentation. Here are some common scenarios where you might need to sort a slice:
Displaying Sorted Data
Improving Search Efficiency
Custom Ranking or Prioritization
Data Cleaning and Organization
SortFunc function
In order to sort a slice we can use the slices.SortFunc function.
The slices.SortFunc function receives a slice and a comp function in order to sort the values. This comp function should return -1 if a < b, 1 if a > b and 0 if the values are equals.
var mySlice []string
mySlice = append(mySlice, "A")
mySlice = append(mySlice, "B")
mySlice = append(mySlice, "C")
mySlice = append(mySlice, "Z")
mySlice = append(mySlice, "M")
mySlice = append(mySlice, "Y")
mySlice = append(mySlice, "P")
slices.SortFunc(mySlice, func(a, b string) int {
return strings.Compare(a, b)
})
for _, v := range mySlice {
fmt.Println(v)
}
>>> A
>>> B
>>> C
>>> M
>>> P
>>> Y
>>> Z
If we would like to sort a slice of integer, we could change the function this way:
var mySlice []int
mySlice = append(mySlice, 55)
mySlice = append(mySlice, 53)
mySlice = append(mySlice, 105)
mySlice = append(mySlice, 3)
mySlice = append(mySlice, 375)
mySlice = append(mySlice, 376)
mySlice = append(mySlice, 377)
mySlice = append(mySlice, 250)
mySlice = append(mySlice, 15)
slices.SortFunc(mySlice, func(a, b int) int {
return a - b
})
for _, v := range mySlice {
fmt.Println(v)
}
>>> 3
>>> 15
>>> 53
>>> 55
>>> 105
>>> 250
>>> 375
>>> 376
>>> 377
Sorting a map
If we need to sort a map, we can create a struct in order to hold the values of the map, and then we can sort a slice of this struct.
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
fmt.Println("Starting")
var myMap = map[string]int{
"G": 7,
"B": 2,
"C": 3,
"E": 5,
"A": 1,
"D": 4,
"H": 8,
"F": 6,
}
type kv struct {
Key string
Value int
}
var kvSlice []kv
for k, v := range myMap {
kvSlice = append(kvSlice, kv{Key: k, Value: v})
}
for k, v := range kvSlice {
fmt.Println(k, v)
}
fmt.Println("----------")
slices.SortFunc(kvSlice, func(a, b kv) int {
return strings.Compare(a.Key, b.Key)
})
for k, v := range kvSlice {
fmt.Println(k, v)
}
}
>>> 55
>>> 53
>>> 105
>>> 3
>>> 375
>>> 376
>>> 377
>>> 250
>>> 15
>>> ----------
>>> 3
>>> 15
>>> 53
>>> 55
>>> 105
>>> 250
>>> 375
>>> 376
>>> 377