Skip to content

Make a Report Deterministic

The Course
•
25 min study

The queue's list command prints every task. If it ranged over the map directly, the same queue could print its tasks in a different order on each run, because Go deliberately varies map iteration order. A person reading the list would be confused, and a check that compares the exact output, which you will write on Day 6, would pass on one run and fail on the next.

A map is good for lookup, but its iteration order is unspecified. Collect the keys into a slice, sort it with slices.Sort and use its order for the report. Sorting changes only the key slice; the map is untouched.

Predict and run

In what order do the titles appear?

Predict, then run Go
package main

import (
	"fmt"
	"slices"
)

func main() {
	tasks := map[int]string{9: "Review", 2: "Read", 5: "Draft"}
	ids := make([]int, 0, len(tasks))
	for id := range tasks {
		ids = append(ids, id)
	}
	slices.Sort(ids)
	for _, id := range ids {
		fmt.Println(id, tasks[id])
	}
}
Check your prediction
Text
2 Read
5 Draft
9 Review

Add ID 1. Predict where the new record appears.

Sort records with a function

slices.Sort works for values that already have an order, such as numbers and strings. To order records by one of their fields, call slices.SortFunc and pass a function literal: a function written inline, without a name. It receives two records, a and b, and returns a negative number when a belongs first, zero when they tie and a positive number when b belongs first. cmp.Compare returns exactly that for two numbers or two strings. The task queue's Tasks method sorts its snapshot this way.

Sort records by ID Go
package main

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

type Task struct {
	ID    int
	Title string
}

func main() {
	tasks := []Task{{9, "Review"}, {2, "Read"}, {5, "Draft"}}
	slices.SortFunc(tasks, func(a, b Task) int {
		return cmp.Compare(a.ID, b.ID)
	})
	fmt.Println(tasks)
}
Text
[{2 Read} {5 Draft} {9 Review}]

Swap a.ID and b.ID and predict the new order. Then compare a.Title with b.Title to sort by title instead.

Practice

Exercise

Your turn

The starter has tasks with a due day. Sort them so the earliest due day comes first, and tasks due on the same day are in alphabetical order by title. The output should be:

Text
1 Email Sam
1 Read notes
3 Book room
3 Draft agenda
Your working space Go
package main

import (
	"fmt"
)

type Task struct {
	Due   int
	Title string
}

func main() {
	tasks := []Task{{3, "Draft agenda"}, {1, "Read notes"}, {3, "Book room"}, {1, "Email Sam"}}
	for _, t := range tasks {
		fmt.Println(t.Due, t.Title)
	}
}
Hint 1: the idea

One comparison function decides the whole order. It compares due days first, and only when they tie does it look at the titles.

Hint 2: a first step

Sort by due day alone with slices.SortFunc and cmp.Compare(a.Due, b.Due). The days come out right, but the ties may not be alphabetical. Then store that comparison in a variable and return it only when it isn't zero.

Worked solution
Run the solution Go
package main

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

type Task struct {
	Due   int
	Title string
}

func main() {
	tasks := []Task{{3, "Draft agenda"}, {1, "Read notes"}, {3, "Book room"}, {1, "Email Sam"}}
	slices.SortFunc(tasks, func(a, b Task) int {
		if byDue := cmp.Compare(a.Due, b.Due); byDue != 0 {
			return byDue
		}
		return cmp.Compare(a.Title, b.Title)
	})
	for _, t := range tasks {
		fmt.Println(t.Due, t.Title)
	}
}
Text
1 Email Sam
1 Read notes
3 Book room
3 Draft agenda

Without the tie-break, the order of two tasks due on the same day is up to the sorting algorithm, so a report could change between Go versions. The tie-break makes every pair of distinct tasks compare as unequal, and the output is fully determined. The queue sorts by ID, which is unique, so it never needs one.

Was this article helpful?

Your response is saved on this device.