WeCodeAcademy

Go Sorting

ExampleGo
package main

import (
  "fmt"
  "sort"
  "strings"
)

type Person struct {
  Name string
  Age  int
}

func main() {
  nums := []int{5, 2, 9, 1}
  sort.Ints(nums)
  fmt.Println(nums)

  words := []string{"pear", "fig", "banana"}
  sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
  fmt.Println(words)

  people := []Person{{"Ada", 36}, {"Sam", 22}, {"Lee", 41}}
  sort.Slice(people, func(i, j int) bool { return people[i].Age > people[j].Age })
  fmt.Println(people)

  fmt.Println(strings.Compare("a", "b"))
}
Output
[1 2 5 9]
[fig pear banana]
[{Lee 41} {Ada 36} {Sam 22}]
-1

sort.Slice takes a function that says whether item i should come before item j, so you can sort by any rule.

Quick check

What does the function given to sort.Slice return?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.