0Pricing
Go Academy · Lesson

Custom Sort Orders

Define comparison functions.

Beyond Default Order

Default sorting goes ascending. But real data needs custom rules: sort by length, by multiple fields, or by a computed value.

The comparison function is where you express any rule you want.

The Less Function

A comparison function for sort.Slice has the signature func(i, j int) bool. It returns true when element i belongs before element j.

package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{4, 1, 3}
	less := func(i, j int) bool { return nums[i] < nums[j] }
	sort.Slice(nums, less)
	fmt.Println(nums)
}

All lessons in this course

  1. Sorting Slices
  2. Custom Sort Orders
  3. Searching Sorted Data
  4. Stable Sorting
← Back to Go Academy