Skip to content

On Your Own: An Equipment Loan Register

The Course
•
50 min study

The task queue protected one rule per record: an ID is added once, and a task is finished once. This project asks you to apply the same design to a different set of rules, without a lesson to follow. A club lends out equipment. The register knows a fixed set of items, and each item is either available or on loan.

Requirements

  • Item IDs are strings, short lower-case names such as drill and tent. Store availability in a map from ID to a flag.

  • NewRegister(ids []string) *Register creates a register in which every listed item is available. No other item is ever added: commands about unknown IDs are rejected and leave the map unchanged.

  • Borrow(id string) error succeeds only for an available item. Return(id string) error succeeds only for an item on loan.

  • Three sentinel errors, each wrapped with the item ID using %w. The messages must be exactly item not found, item is already on loan and item is not on loan, so a wrapped rejection reads item tent: item is already on loan.

  • run(reg *Register, r io.Reader, w io.Writer) error reads borrow ID and return ID commands, one per line, and skips blank lines. Line numbers count every line, including blank ones. It writes:

    • OK followed by the command for each success, for example OK borrow tent;
    • Line N: followed by the error for each rejection, for example Line 2: item tent: item is already on loan;
    • Line N: unknown command "fix" for a verb it doesn't know.

    A rejected command never stops the loop. A failed write stops it and is returned, wrapped with its line number.

  • Checks in main, using panic on a mismatch: every successful transition and every rejection with errors.Is, that an unknown ID stays unknown, the full transcript below, and that a failing writer's error reaches the caller. After the checks pass, print the transcript and then Loan register checks passed.

Sample input and transcript

Use a register with drill and tent, and this input, which has a blank third line:

Text
borrow tent
borrow tent

return tent
return drill
borrow kayak
fix tent

run must write exactly this, with a newline after every line:

Text
OK borrow tent
Line 2: item tent: item is already on loan
OK return tent
Line 5: item drill: item is not on loan
Line 6: item kayak: item not found
Line 7: unknown command "fix"
Exercise

Your turn

Build the register, run and the checks described above. When everything passes, your program prints:

Text
OK borrow tent
Line 2: item tent: item is already on loan
OK return tent
Line 5: item drill: item is not on loan
Line 6: item kayak: item not found
Line 7: unknown command "fix"
Loan register checks passed
Your working space Go
package main

func main() {
	// Define the register, its errors and run, then check them.
}
Hint 1: the idea

Keep the rules in methods that return errors and keep the console in run. Then each part can be checked on its own, just as Queue and run were.

Hint 2: a first step

Store availability in a map[string]bool. In Borrow, look up the ID with the two-result form first, then check the flag before writing false.

Worked solution
Run the solution Go
package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"strings"
)

var (
	errUnknown   = errors.New("item not found")
	errOnLoan    = errors.New("item is already on loan")
	errNotLoaned = errors.New("item is not on loan")
	errClosed    = errors.New("destination closed")
)

type Register struct {
	available map[string]bool
}

func NewRegister(ids []string) *Register {
	reg := &Register{available: make(map[string]bool)}
	for _, id := range ids {
		reg.available[id] = true
	}
	return reg
}

func (reg *Register) Borrow(id string) error {
	available, ok := reg.available[id]
	if !ok {
		return fmt.Errorf("item %s: %w", id, errUnknown)
	}
	if !available {
		return fmt.Errorf("item %s: %w", id, errOnLoan)
	}
	reg.available[id] = false
	return nil
}

func (reg *Register) Return(id string) error {
	available, ok := reg.available[id]
	if !ok {
		return fmt.Errorf("item %s: %w", id, errUnknown)
	}
	if available {
		return fmt.Errorf("item %s: %w", id, errNotLoaned)
	}
	reg.available[id] = true
	return nil
}

func run(reg *Register, r io.Reader, w io.Writer) error {
	scanner := bufio.NewScanner(r)
	lineNumber := 0
	for scanner.Scan() {
		lineNumber++
		line := strings.TrimSpace(scanner.Text())
		if line == "" {
			continue
		}
		verb, id, _ := strings.Cut(line, " ")
		var err error
		switch verb {
		case "borrow":
			err = reg.Borrow(id)
		case "return":
			err = reg.Return(id)
		default:
			err = fmt.Errorf("unknown command %q", verb)
		}
		message := "OK " + line
		if err != nil {
			message = fmt.Sprintf("Line %d: %v", lineNumber, err)
		}
		if _, err := fmt.Fprintln(w, message); err != nil {
			return fmt.Errorf("write line %d: %w", lineNumber, err)
		}
	}
	return scanner.Err()
}

type brokenWriter struct{}

func (brokenWriter) Write([]byte) (int, error) {
	return 0, errClosed
}

func expect(name string, got, want error) {
	if !errors.Is(got, want) {
		panic(fmt.Sprintf("%s: got %v, want %v", name, got, want))
	}
}

func main() {
	reg := NewRegister([]string{"drill", "tent"})
	expect("borrow", reg.Borrow("drill"), nil)
	expect("repeat borrow", reg.Borrow("drill"), errOnLoan)
	expect("return", reg.Return("drill"), nil)
	expect("repeat return", reg.Return("drill"), errNotLoaned)
	expect("unknown", reg.Borrow("kayak"), errUnknown)
	expect("still unknown", reg.Return("kayak"), errUnknown)

	var out strings.Builder
	input := "borrow tent\nborrow tent\n\nreturn tent\nreturn drill\nborrow kayak\nfix tent\n"
	want := "OK borrow tent\n" +
		"Line 2: item tent: item is already on loan\n" +
		"OK return tent\n" +
		"Line 5: item drill: item is not on loan\n" +
		"Line 6: item kayak: item not found\n" +
		"Line 7: unknown command \"fix\"\n"
	if err := run(NewRegister([]string{"drill", "tent"}), strings.NewReader(input), &out); err != nil {
		panic(err)
	}
	if out.String() != want {
		panic(fmt.Sprintf("unexpected transcript: %q", out.String()))
	}
	err := run(NewRegister([]string{"tent"}), strings.NewReader("borrow tent"), brokenWriter{})
	expect("write failure", err, errClosed)

	fmt.Print(out.String())
	fmt.Println("Loan register checks passed")
}
Text
OK borrow tent
Line 2: item tent: item is already on loan
OK return tent
Line 5: item drill: item is not on loan
Line 6: item kayak: item not found
Line 7: unknown command "fix"
Loan register checks passed

Borrow and Return check that the item exists before they read its flag, so a missing ID never writes to the map. errors.Is(nil, nil) is true, so expect checks successes and rejections the same way. Rejections keep the loop running, but a write failure ends it, as in the task queue. The "still unknown" check works whichever way a buggy Borrow might have stored kayak: as available, Return would say it isn't on loan; as on loan, Return would succeed. Only an unchanged map gives errUnknown twice.

Check your own work

Go through this list before you open the solution, or after. Each item is a mistake the sample transcript alone might not catch.

  • Unknown IDs stay unknown. Borrow kayak, then return kayak: both must be rejected as item not found.
  • Rejections change nothing. After borrow tent fails because the tent is on loan, the tent is still on loan, and returning it succeeds.
  • Errors are recognisable, not just readable. Your checks use errors.Is with the sentinels. Change one %w to %v and at least one check must fail.
  • Blank lines are skipped but counted. Remove the blank line from the sample input and the later line numbers must each drop by one.
  • A write failure stops the run. With a writer that always fails, run returns an error that errors.Is matches to the writer's error, after the first line.
  • The rules live in methods. run decides what to print, but never reads or writes the map itself.

Was this article helpful?

Your response is saved on this device.