Skip to content

Protect Unique IDs

The Course
•
30 min study

The last lesson's map could be changed by any line of code: one careless tasks[id] = task and a duplicate ID silently replaces an existing task. The queue needs one rule to hold always: an ID is added once. The way to make a rule hold is to have exactly one place that writes the map, and to send every change through it.

Keep the map inside a Queue struct and expose an Add method. A duplicate ID fails before any update. A nil map can be read, but writing to it stops the program with panic: assignment to entry in nil map, so Add creates the map on the first accepted add. That makes the zero value, var queue Queue, ready to use.

Predict and run

Which title survives the duplicate attempt?

Predict, then run Go
package main

import (
	"fmt"
)

type Queue struct{ tasks map[int]string }

func (q *Queue) Add(id int, title string) bool {
	if _, exists := q.tasks[id]; exists {
		return false
	}
	if q.tasks == nil {
		q.tasks = make(map[int]string)
	}
	q.tasks[id] = title
	return true
}

func (q *Queue) Title(id int) string { return q.tasks[id] }

func main() {
	var queue Queue
	fmt.Println(queue.Add(2, "Read"))
	fmt.Println(queue.Add(2, "Replace"))
	fmt.Println(queue.Title(2))
}
Check your prediction
Text
true
false
Read

Add a different ID and print queue.Title for it.

What a lower-case field protects, and what it doesn't

The field is named tasks, with a lower-case first letter. In Go, a name that starts with a lower-case letter is unexported: code in other packages can't use it. You have already relied on this. strings.Builder keeps its text in an unexported field called buf, and writing b.buf in your program fails:

Text
./main.go:7:8: b.buf undefined (cannot refer to unexported field buf)

So outside its package, a Builder can only be changed through its methods, and its rules can't be bypassed. A package is a folder of .go files that start with the same package line. Everything in this course, including the capstone, lives in one package, main. Inside one package, every file can see every name, so main could still write queue.tasks[2] = "Replace" and skip the duplicate check entirely. The compiler won't stop it.

That means two things for this course:

  • Inside package main, the lower-case field is a promise, not a lock. Keep it by reading and writing the queue only through its methods, as the example now does with Title instead of queue.tasks[2].
  • When the queue moves into a package of its own, which real projects do, the same lower-case field becomes a lock: other packages can't reach the map, and Add is the only way in. Writing your code as if that were already true costs nothing and makes the move easy.

A constructor function

The zero value of this Queue works because Add creates the map when needed. When a type needs set-up that a zero value can't give it, Go code uses an ordinary function, by convention named New plus the type, that builds the value and returns a pointer to it:

Go
func NewQueue() *Queue {
	return &Queue{tasks: make(map[int]string)}
}

&Queue{...} builds a Queue and takes its address in one step. Callers write queue := NewQueue() and then queue.Add(...) as before. The Day 7 project needs no constructor, because its zero value works. You will see one in the Day 7 on-your-own model solution.

Practice

Exercise

Your turn

Add a Rename(id int, title string) error method to the queue. It returns an error for an ID that isn't in the queue and for a blank title, and otherwise stores the new title. main must use only methods, never queue.tasks. The starter tries three renames and prints this once Rename works:

Text
task 9 not found
title is required
Outline
Your working space Go
package main

import (
	"fmt"
)

type Queue struct{ tasks map[int]string }

func (q *Queue) Add(id int, title string) bool {
	if _, exists := q.tasks[id]; exists {
		return false
	}
	if q.tasks == nil {
		q.tasks = make(map[int]string)
	}
	q.tasks[id] = title
	return true
}

func (q *Queue) Title(id int) string { return q.tasks[id] }

func (q *Queue) Rename(id int, title string) error {
	return nil
}

func main() {
	var queue Queue
	queue.Add(3, "Read")
	for _, err := range []error{queue.Rename(9, "Draft"), queue.Rename(3, "  "), queue.Rename(3, "Outline")} {
		if err != nil {
			fmt.Println(err)
		}
	}
	fmt.Println(queue.Title(3))
}
Hint 1: the idea

Rename is a second place that writes the map, so it must protect the same thing Add does: only IDs that exist change, and only to a real title. Check both before you write.

Hint 2: a first step

Start with the comma-ok lookup, if _, exists := q.tasks[id]; !exists, returning an error made with fmt.Errorf("task %d not found", id). The first line of output should appear. Then check strings.TrimSpace(title), adding "strings" to the imports.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"strings"
)

type Queue struct{ tasks map[int]string }

func (q *Queue) Add(id int, title string) bool {
	if _, exists := q.tasks[id]; exists {
		return false
	}
	if q.tasks == nil {
		q.tasks = make(map[int]string)
	}
	q.tasks[id] = title
	return true
}

func (q *Queue) Title(id int) string { return q.tasks[id] }

func (q *Queue) Rename(id int, title string) error {
	if _, exists := q.tasks[id]; !exists {
		return fmt.Errorf("task %d not found", id)
	}
	title = strings.TrimSpace(title)
	if title == "" {
		return errors.New("title is required")
	}
	q.tasks[id] = title
	return nil
}

func main() {
	var queue Queue
	queue.Add(3, "Read")
	for _, err := range []error{queue.Rename(9, "Draft"), queue.Rename(3, "  "), queue.Rename(3, "Outline")} {
		if err != nil {
			fmt.Println(err)
		}
	}
	fmt.Println(queue.Title(3))
}
Text
task 9 not found
title is required
Outline

Without the existence check, Rename(9, "Draft") would quietly add task 9, and the queue's "added once, through Add" rule would be broken by a method that was only meant to rename. Rename also works on a zero-value queue: looking up a key in a nil map is safe, and the write is reached only for an ID that exists, so the map is never nil there.

Was this article helpful?

Your response is saved on this device.