The following code should create an array of ints (a
) and sort it, but sort.Sort does not appear to modify the variable.
package main
import (
"fmt"
"sort"
)
type IntArray [5]int
type byNum [5]int
func (s byNum) Len() int {
return len(s)
}
func (s byNum) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byNum) Less(i, j int) bool {
return s[i] < s[j]
}
func main() {
a := IntArray{5,3,4,1,2}
fmt.Println(a)
sort.Sort(byNum(a))
fmt.Println(a)
}
https://play.golang.org/p/bhcwgosqvis
[5 3 4 1 2]
[5 3 4 1 2]
Program exited.
Why does this not work?
The problem is that the Swap method is changing the argument array, not the array in the caller.
Fix by declaring byNum as a slice:
type byNum []int
...
sort.Sort(byNum(a[:]))
In this call, the backing array of the slice argument is the array that you want to modify.