Sorting And Go Slices
Word of caution for anyone passing Go slices to a function which will sort them. Doing so as is will modify the original slice. If you were to write this, for example:
package main
import (
"fmt"
"sort"
)
func printSorted(ys []int) {
sort.Slice(ys, func(i, j int) bool { return ys[i] < ys[j] })
fmt.Println(ys)
}
func main() {
xs := []int{3, 1, 2}
printSorted(xs)
fmt.Println(xs)
}
You will find, when you run it, that both xs
and ys
will be sorted:
[1,2,3]
[1,2,3]
If this is not desired, the remedy would be make a copy of the slice prior to sorting it:
func printSorted(ys []int) {
ysDup := make([]int, len(ys))
copy(ysDup, ys)
sort.Slice(ysDup, func(i, j int) bool { return ys[i] < ys[j] })
fmt.Println(ysDup)
}
This make sense when you consider that the elements of a slice are more or less stored in a normal array. Slices add things like start and end items, which are stored as values within the slice struct, but the array itself is just a normal reference and it is this that sort.Slice will modify.
On the face of it, this is a pretty trivial thing to find out. But it’s worth noting here just so that I don’t have to remember it again.