0Pricing
Go Academy · Lesson

Custom Sort Orders

Define comparison functions.

Custom Sort Orders is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)
}

Sort by String Length

Instead of alphabetical, compare len() of each string to order by length.

package main

import (
	"fmt"
	"sort"
)

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

Sort Structs by Field

Pick any struct field for the comparison. Here we sort products by price.

package main

import (
	"fmt"
	"sort"
)

type Product struct {
	Name  string
	Price int
}

func main() {
	items := []Product{{"Pen", 3}, {"Book", 12}, {"Cup", 7}}
	sort.Slice(items, func(i, j int) bool {
		return items[i].Price < items[j].Price
	})
	fmt.Println(items)
}

Multi-Field Sorting

To break ties, compare a second field when the first is equal. Sort by age, then by name.

package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := []Person{{"Zoe", 30}, {"Ann", 30}, {"Bob", 25}}
	sort.Slice(p, func(i, j int) bool {
		if p[i].Age != p[j].Age {
			return p[i].Age < p[j].Age
		}
		return p[i].Name < p[j].Name
	})
	fmt.Println(p)
}

Reverse with sort.Reverse

sort.Reverse wraps a sort.Interface to flip its order. It pairs with helpers like sort.IntSlice.

package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{1, 4, 2, 3}
	sort.Sort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println(nums)
}

The sort.Interface

For full control, implement sort.Interface: three methods Len(), Less(i, j int) bool, and Swap(i, j int).

package main

import (
	"fmt"
	"sort"
)

type ByLen []string

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

func main() {
	w := []string{"ccc", "a", "bb"}
	sort.Sort(ByLen(w))
	fmt.Println(w)
}

Sorting by Computed Value

The comparison can use any expression. Sort numbers by their absolute distance from zero.

package main

import (
	"fmt"
	"sort"
)

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

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

Case-Insensitive Sort

Use strings.ToLower inside the comparison to ignore case when ordering strings.

package main

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

func main() {
	w := []string{"banana", "Apple", "cherry"}
	sort.Slice(w, func(i, j int) bool {
		return strings.ToLower(w[i]) < strings.ToLower(w[j])
	})
	fmt.Println(w)
}

Slice vs Interface

Two ways to customize order:

  • sort.Slice - quick, inline less function
  • sort.Interface - reusable named type with three methods

Prefer sort.Slice for one-off sorts.

Keep Comparisons Pure

A comparison function should only read elements and return a bool. It must not modify the slice or have side effects, or the sort may behave unpredictably.

Quick Check

You want to sort people by age, and by name when ages are equal. What technique do you use?

Recap

You can define any sort order:

  • The less function expresses your rule
  • Multi-field sorts compare a second field on ties
  • sort.Reverse flips order; sort.Interface gives reusable types

Frequently asked questions

Is the “Custom Sort Orders” lesson free?

Yes — the full text of “Custom Sort Orders” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Custom Sort Orders”?

Define comparison functions. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Custom Sort Orders” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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