Sort

sort package defines an interface whose name is Interface:

  1. type Interface interface {
  2. // Len is the number of elements in the collection.
  3. Len() int
  4. // Less reports whether the element with
  5. // index i should sort before the element with index j.
  6. Less(i, j int) bool
  7. // Swap swaps the elements with indexes i and j.
  8. Swap(i, j int)
  9. }

For slice, or any other collection types, provided that it implements the Len(), Less and Swap functions, you can use sort.Sort() function to arrange the elements in the order.

Let’s see the following example:

  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type command struct {
  7. name string
  8. }
  9. type byName []command
  10. func (a byName) Len() int { return len(a) }
  11. func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  12. func (a byName) Less(i, j int) bool { return a[i].name < a[j].name }
  13. func main() {
  14. c := []command{
  15. {"breakpoint"},
  16. {"help"},
  17. {"args"},
  18. {"continue"},
  19. }
  20. fmt.Println("Before sorting: ", c)
  21. sort.Sort(byName(c))
  22. fmt.Println("After sorting: ", c)
  23. }

To avoid losing focus of demonstrating how to use sort.Interface, the command struct is simplified to only contain one string member: name. The comparison method (Less) is just contrasting the name in alphabetic order.

Check the running result of the program:

  1. Before sorting: [{breakpoint} {help} {args} {continue}]
  2. After sorting: [{args} {breakpoint} {continue} {help}]

We can see after sorting, the items in c are rearranged.

Additionally, if you pick at the performance, you may define a slice whose type is the pointer, because switching pointer is much quicker if the size of element is very big. Modify the above example:

  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type command struct {
  7. name string
  8. help string
  9. }
  10. type byName []*command
  11. func (a byName) Len() int { return len(a) }
  12. func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  13. func (a byName) Less(i, j int) bool { return a[i].name < a[j].name }
  14. func main() {
  15. c := []*command{
  16. {"breakpoint", "Set breakpoints"},
  17. {"help", "Show help"},
  18. {"args", "Print arguments"},
  19. {"continue", "Continue"},
  20. }
  21. fmt.Println("Before sorting: ", c)
  22. sort.Sort(byName(c))
  23. fmt.Println("After sorting: ", c)
  24. }

Check the executing result:

  1. Before sorting: [0xc0820066a0 0xc0820066c0 0xc0820066e0 0xc082006700]
  2. After sorting: [0xc0820066e0 0xc0820066a0 0xc082006700 0xc0820066c0]

You can see the pointers are reordered.

Reference:
The Go Programming Language.