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 (

func printSorted(ys []int) {
	sort.Slice(ys, func(i, j int) bool { return ys[i] < ys[j] })

func main() {
	xs := []int{3, 1, 2}

You will find, when you run it, that both xs and ys will be sorted:


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] })

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.