typestar

sort.Interface and slices.SortFunc in Go

The old three-method way, and the generic one that replaced it.

type Step struct {
    Title string
    Stars int
}

type byStars []Step

func (s byStars) Len() int           { return len(s) }
func (s byStars) Less(i, j int) bool { return s[i].Stars < s[j].Stars }
func (s byStars) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

func sortBothWays(steps []Step) []string {
    sort.Sort(byStars(steps))
    oldest := steps[0].Title

    slices.SortFunc(steps, func(a, b Step) int {
        return cmp.Or(cmp.Compare(b.Stars, a.Stars),
            cmp.Compare(a.Title, b.Title))
    })
    return []string{oldest, steps[0].Title}
}

How it works

  1. sort.Interface needs Len, Less and Swap.
  2. slices.SortFunc takes a comparison and no boilerplate.
  3. cmp.Compare writes the comparison for ordered types.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
519
Tokens
184
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 105 seconds.

Type this snippet

Step 3 of 3 in Standard interfaces, step 12 of 19 in Interfaces & generics.

← Previous Next →