Skip to content

From Reading Records to Tasks

The Course
•
25 min study

The beginner reading log collected records in order. This course builds a task queue whose records have stable IDs and can change state. You will reuse structs, slices and returned errors to build an API that protects those records.

A queue holds many integers that mean different things: a task's ID, how many tasks are open, a line number in the input. If they are all plain int, nothing stops finish(openCount) from compiling and quietly finishing the wrong task. A named type such as type TaskID int gives one meaning its own type. It stores the same whole number underneath, but the compiler now refuses to mix it with other integers by accident.

Predict and run

Why do the first two IDs work while zero is rejected?

Predict, then run Go
package main

import (
	"fmt"
)

type TaskID int

func main() {
	for _, id := range []TaskID{2, 1, 0} {
		if id <= 0 {
			fmt.Println("Invalid ID")
			continue
		}
		fmt.Println("Task", id)
	}
}
Check your prediction
Text
Task 2
Task 1
Invalid ID

Change the input to include -1 and 1.

What the named type catches

Here is the mistake a named type exists to stop. count is an ordinary int, and the program tries to use it as an ID:

Go
count := 3
var id TaskID = count

The compiler rejects it:

Text
./main.go:9:18: cannot use count (variable of type int) as TaskID value in variable declaration

TaskID and int share a representation but are different types, so Go won't convert one into the other silently. When you really do mean "this integer is an ID", say so with a conversion: the type name used like a function, TaskID(count). A literal number such as 2 needs no conversion, because an untyped constant takes whatever type the context asks for. That is why []TaskID{2, 1, 0} above compiles.

Convert on purpose Go
package main

import (
	"fmt"
)

type TaskID int

func describe(id TaskID) string {
	return fmt.Sprintf("task #%d", id)
}

func main() {
	count := 3
	id := TaskID(count)
	fmt.Println(describe(id))
	fmt.Println(describe(7))
	fmt.Println(describe(TaskID(-4)))
}
Text
task #3
task #7
task #-4

Trace the three calls. TaskID(count) turns the variable into an ID. The literal 7 becomes a TaskID because describe asks for one. The last line shows the limit of a named type: TaskID(-4) compiles, because a conversion only changes the type and never checks the value. Writing describe(count) would fail to compile, just like the declaration above.

A conversion is not a check

So the type keeps IDs apart from other integers, and something else has to keep IDs valid. Put that check at the point where input enters the program, in a function that is the only way to make a TaskID from outside data. It returns an error for a bad value and converts only after the check passes. The capstone does this when it parses each command.

Exercise

Your turn

Write newID, which takes an int and returns a TaskID and an error. It accepts only positive values and converts them, and returns 0 with an error for anything else. The starter calls it for 3, 0 and -2, so it prints this once newID works:

Text
Task 3
-> ID must be positive, got 0
-> ID must be positive, got -2
Your working space Go
package main

import (
	"fmt"
)

type TaskID int

func newID(value int) (TaskID, error) {
	// Replace this line with the check and the conversion.
	return 0, nil
}

func main() {
	for _, input := range []int{3, 0, -2} {
		id, err := newID(input)
		if err != nil {
			fmt.Println("->", err)
			continue
		}
		fmt.Println("Task", id)
	}
}
Hint 1: the idea

Validate the plain int first. Only a value that passed becomes a TaskID, so no caller can get an invalid ID from this function.

Hint 2: a first step

Write return TaskID(value), nil as the last line and run it. You should see Task 3, Task 0 and Task -2. Then add the check above it, building the message with fmt.Errorf.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

type TaskID int

func newID(value int) (TaskID, error) {
	if value <= 0 {
		return 0, fmt.Errorf("ID must be positive, got %d", value)
	}
	return TaskID(value), nil
}

func main() {
	for _, input := range []int{3, 0, -2} {
		id, err := newID(input)
		if err != nil {
			fmt.Println("->", err)
			continue
		}
		fmt.Println("Task", id)
	}
}
Text
Task 3
-> ID must be positive, got 0
-> ID must be positive, got -2

The type keeps IDs separate from counts in every signature that mentions TaskID. newID keeps them valid, because it converts only after the check. Returning TaskID(value) with no check at all would compile just as happily, and that is exactly why the check has to be written by you.

Was this article helpful?

Your response is saved on this device.