Tsallaka zuwa abun ciki
Justice Tech School

Sorting

sort.Ints and sort.Strings sort basic slices. slices.SortFunc and sort.Slice take a function for custom orders.

Example
package main

import (
	"fmt"
	"cmp"
	"slices"
	"sort"
)

func main() {
	n := []int{3, 1, 2}
	sort.Ints(n)
	type P struct {
		Name string
		Age  int
	}
	ps := []P{{"Zed", 20}, {"Ada", 30}, {"Bob", 20}}
	slices.SortFunc(ps, func(a, b P) int {
		if c := cmp.Compare(a.Age, b.Age); c != 0 {
			return c
		}
		return cmp.Compare(a.Name, b.Name)
	})
	fmt.Println(n, ps)
}

Result

[1 2 3] [{Bob 20} {Zed 20} {Ada 30}]

Exercise

Sort integers.

sort.(n)

Quiz Test

Which takes a custom comparison?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.