Thuta Learning
Go
ProjectsProgrammingBeginner

Mini Project: Task Manager (Part 2) - Methods & Error Handling

GoLesson 2940 min

What you'll walk away with

  • Group the slice and an ID counter in a TaskManager struct whose zero value is ready to use
  • Explain why methods that change state need a pointer receiver
  • Create sentinel errors with errors.New and wrap them with context using %w
  • Check errors with if err != nil and tell them apart with errors.Is

Explain it simply

Explain it simply

In Part 1, the tasks slice was handed to every function and handed back again. In this part we give the slice to a TaskManager, a manager that owns it. To add a task you ask the manager to Add; to finish one you ask it to Complete.

A good manager does not silently skip a job it cannot do; it reports back: "there is no task with ID 5". In Go that report is an error value. Every method returns one, and the caller decides what to do about it.

Problem → Why → Solution

The problem: the method runs, but nothing changes

When people first write TaskManager, they often declare the receiver by value: (m TaskManager). They call Add twice, then List, and see only "Task list is empty." There is no compile error and no panic, so they lose time suspecting the append inside Add.

Inside Add, m.tasks really does grow. But what grows is a copy made for that single call, not the manager in main. When the method returns, the copy disappears.

main.go
func (m TaskManager) Add(title string) { // value receiver: m is a copy
	m.nextID++
	m.tasks = append(m.tasks, Task{ID: m.nextID, Title: title})
}

func main() {
	var m TaskManager
	m.Add("Learn Go basics")
	m.List() // Task list is empty.
}

A receiver is just a parameter

A method receiver behaves like a function parameter. (m TaskManager) copies the whole struct, including the slice header and nextID. (m *TaskManager) passes the struct's address, so the method changes the manager in main directly. Every method that must change state needs a pointer receiver.

Core concept: a type that owns its state, and errors as values

The Part 2 design comes down to four decisions, and each one fixes a problem you met in Part 1.

1. Gather the state in one struct

TaskManager keeps tasks and nextID as lowercase, unexported fields, so code outside the package cannot edit the slice directly; it has to go through the methods. Both zero values, a nil slice and 0, are useful, so &TaskManager{} works without a constructor.

2. Use pointer receivers

Add, Complete and Remove change state, so they need a *TaskManager receiver. List only reads, but Go convention is to keep receivers consistent: once one method needs a pointer, give them all a pointer.

3. Hand out IDs from a counter

len(tasks)+1 produces duplicate IDs after a deletion. nextID only ever goes up, so a deleted ID is never handed out again.

4. Return an error when something fails

Go has no exceptions. A function that can fail returns an error as its last result, and nil on success. A sentinel error such as ErrNotFound is declared once at package level, then fmt.Errorf("remove task %d: %w", id, ErrNotFound) adds context: which operation, which ID. Because of %w, the caller can still find the original with errors.Is(err, ErrNotFound).

How failure is reportedWhat the caller learnsUse it when
bool (Part 1)Only that it failedA lookup with one possible reason
errorWhy it failed, with contextAny operation that can normally fail
panicThe program crashesProgrammer bugs only

One more rule completes the picture: handle each error once. A method either returns the error to its caller, adding context on the way, or handles it itself, for example by printing it or showing a hint.

Doing both, logging inside Remove and also returning the error, prints the same failure twice and clutters the output. In this project the methods only return errors, and main decides how to show them.

Mental model: the manager owns the state and reports back
  1. Caller asks a method
  2. Pointer receiver edits the state
  3. Failure returns a wrapped error
  4. Caller checks it with errors.Is

The error message is for people; errors.Is is for code. Never build logic on comparing message strings.

General pattern

go
var ErrMissing = errors.New("item not found")

type Store struct{ items []Item }

func (s *Store) Change(id int) error {
	i := s.find(id)
	if i < 0 {
		return fmt.Errorf("change %d: %w", id, ErrMissing)
	}
	s.items[i].Field = newValue
	return nil
}

Declare the sentinel error once, give state-changing methods a pointer receiver, return an error wrapped with %w on failure and nil on success.

Part 2 code: TaskManager with error handling

main tries three titles, and Add rejects the third because it is only spaces. Then it completes ID 1, tries to remove ID 5 (which does not exist), really removes ID 2 and adds a new task. Notice in the output that the new task gets ID 3; it does not reuse ID 2.

main.go
package main

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

type Task struct {
	ID    int
	Title string
	Done  bool
}

var (
	ErrEmptyTitle = errors.New("title must not be empty")
	ErrNotFound   = errors.New("task not found")
)

// The zero value is ready to use: &TaskManager{} needs no constructor.
type TaskManager struct {
	tasks  []Task
	nextID int
}

func (m *TaskManager) Add(title string) (Task, error) {
	title = strings.TrimSpace(title)
	if title == "" {
		return Task{}, ErrEmptyTitle
	}
	m.nextID++
	t := Task{ID: m.nextID, Title: title}
	m.tasks = append(m.tasks, t)
	return t, nil
}

func (m *TaskManager) indexOf(id int) int {
	for i, t := range m.tasks {
		if t.ID == id {
			return i
		}
	}
	return -1
}

func (m *TaskManager) Complete(id int) error {
	i := m.indexOf(id)
	if i < 0 {
		return fmt.Errorf("complete task %d: %w", id, ErrNotFound)
	}
	m.tasks[i].Done = true
	return nil
}

func (m *TaskManager) Remove(id int) error {
	i := m.indexOf(id)
	if i < 0 {
		return fmt.Errorf("remove task %d: %w", id, ErrNotFound)
	}
	m.tasks = slices.Delete(m.tasks, i, i+1)
	return nil
}

func (m *TaskManager) List() {
	if len(m.tasks) == 0 {
		fmt.Println("Task list is empty.")
		return
	}
	for _, t := range m.tasks {
		status := "[ ]"
		if t.Done {
			status = "[x]"
		}
		fmt.Printf("%s %d. %s\n", status, t.ID, t.Title)
	}
}

func main() {
	m := &TaskManager{}
	for _, title := range []string{"Learn Go basics", "Build task manager", "   "} {
		if _, err := m.Add(title); err != nil {
			fmt.Println("add failed:", err)
		}
	}

	if err := m.Complete(1); err != nil {
		fmt.Println("error:", err)
	}
	if err := m.Remove(5); err != nil {
		fmt.Println("error:", err)
		if errors.Is(err, ErrNotFound) {
			fmt.Println("hint: list the tasks to see valid IDs")
		}
	}
	if err := m.Remove(2); err != nil {
		fmt.Println("error:", err)
	}

	t, err := m.Add("Write tests")
	if err != nil {
		fmt.Println("add failed:", err)
		return
	}
	fmt.Println("new task gets ID", t.ID)
	m.List()
}

Code breakdown

  1. Sentinel errorsErrNotFound = errors.New("task not found")

    An error value created once at package level. Callers can compare against this same variable with errors.Is.

  2. Validate, then countm.nextID++

    Add trims the title and returns ErrEmptyTitle before touching the counter, so rejected calls never waste an ID number.

  3. Wrap with contextreturn fmt.Errorf("remove task %d: %w", id, ErrNotFound)

    %w keeps ErrNotFound inside the new error and produces the message "remove task 5: task not found". With %v the message would look the same, but errors.Is could no longer find it.

  4. Delete by indexm.tasks = slices.Delete(m.tasks, i, i+1)

    slices.Delete removes index i and shifts the later elements forward. It does the same job as append(m.tasks[:i], m.tasks[i+1:]...) but reads more clearly, and its result is stored back into m.tasks, the same rule as in Part 1.

  5. Check, then classifyif errors.Is(err, ErrNotFound) {

    if err != nil checks whether anything went wrong, then errors.Is looks through the wrapped chain for ErrNotFound and, if found, shows the user a helpful hint.

You should see
add failed: title must not be empty
error: remove task 5: task not found
hint: list the tasks to see valid IDs
new task gets ID 3
[x] 1. Learn Go basics
[ ] 3. Write tests

What this sets up for Part 3

Because TaskManager is now the single owner of the state, new features are easy to add in Part 3: Save and Load methods, plus a sync.Mutex and a dirty flag inside the struct. Callers keep calling Add and Complete exactly as before.

nextID matters in Part 3 as well. After loading tasks from a file, the counter has to be recomputed from the highest ID; otherwise a restarted program would start again at ID 1 and collide with tasks that already exist.

In real projects

In real projects

The Go standard library is full of sentinel errors: io.EOF, fs.ErrNotExist, sql.ErrNoRows and more. Database libraries wrap query errors with context, and application code then uses errors.Is(err, sql.ErrNoRows) to detect "no such row" and return an HTTP 404. The ErrNotFound in this lesson follows exactly that pattern.

In services, letting one type such as TaskManager own the state and change it only through methods helps with both concurrency and testing, because there is exactly one place to add a lock and one place to test. Writing messages like "remove task 5: ...", with the operation and the ID, also makes problems easy to find in the logs. Tests benefit as well: a test can assert errors.Is(err, ErrNotFound) without depending on the exact wording of the message.

Common mistakes

Common mistakes

Using a value receiver

With (m TaskManager), every method edits a copy, so nothing Add or Complete does survives. For a type that changes state, write every receiver as *TaskManager.

Comparing a wrapped error with ==

err == ErrNotFound is false for an error wrapped with %w, because err is a new error ("remove task 5: ...") with ErrNotFound inside it. Use errors.Is(err, ErrNotFound). Checking strings.Contains(err.Error(), "not found") is just as fragile: it breaks the day someone rewords the message.

Forgetting to check the error

Calling m.Remove(5) and ignoring the result compiles fine, while the user believes the task was deleted. Handle every error-returning call with if err := ...; err != nil. Linters such as errcheck can find the calls you missed.

Best practices

Best practices

  • Start error strings in lowercase with no final full stop, because they are often wrapped into longer messages such as "remove task 5: task not found".
  • Name sentinel errors ErrSomething, and export them only when callers need to check for them.
  • Validate input, like trimming the title, inside the method, so every caller gets the same rules.

Mini challenge

A dispatcher that runs scripted commands

Reuse the lesson's TaskManager and write an execute function that runs one command line. Instead of reading the keyboard, run the commands from a string slice one by one, so the output is the same every time.

  • Handle four commands: "add <title>", "done <id>", "rm <id>" and "list"
  • When the ID is not a number, turn the strconv.Atoi failure into a helpful error
  • For an unknown command, return ErrUnknownCommand wrapped with %w
  • execute returns errors instead of printing them; main prints " error: ..."
challenge.go
package main

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

// TODO: paste Task, ErrEmptyTitle, ErrNotFound, TaskManager and its
// methods (Add, Complete, Remove, List) from the lesson.

var ErrUnknownCommand = errors.New("unknown command")

// execute runs one line: "add <title>", "done <id>", "rm <id>" or "list".
func execute(m *TaskManager, line string) error {
	// TODO: split the line into command and argument (strings.Cut)
	// TODO: switch on the command; parse IDs with strconv.Atoi
	// TODO: wrap ErrUnknownCommand for anything else
}

func main() {
	script := []string{"add Buy milk", "add Call the bank", "add",
		"done 1", "rm two", "rm 7", "edit 2", "list"}
	m := &TaskManager{}
	for _, line := range script {
		fmt.Println(">", line)
		// TODO: run execute and print "  error: ..." when it fails
	}
}

Expected: The two adds print added #1 and added #2; the empty add, "two", ID 7 and "edit" each print one error line; the final list shows [x] 1. Buy milk and [ ] 2. Call the bank.

Show hint

strings.Cut(line, " ") splits the command from the rest. "done" and "rm" parse the ID the same way, so they can share one case: case "done", "rm":.

Show solution
challenge.go
package main

import (
	"errors"
	"fmt"
	"slices"
	"strconv"
	"strings"
)

type Task struct {
	ID    int
	Title string
	Done  bool
}

var (
	ErrEmptyTitle     = errors.New("title must not be empty")
	ErrNotFound       = errors.New("task not found")
	ErrUnknownCommand = errors.New("unknown command")
)

type TaskManager struct {
	tasks  []Task
	nextID int
}

func (m *TaskManager) Add(title string) (Task, error) {
	title = strings.TrimSpace(title)
	if title == "" {
		return Task{}, ErrEmptyTitle
	}
	m.nextID++
	t := Task{ID: m.nextID, Title: title}
	m.tasks = append(m.tasks, t)
	return t, nil
}

func (m *TaskManager) indexOf(id int) int {
	return slices.IndexFunc(m.tasks, func(t Task) bool { return t.ID == id })
}

func (m *TaskManager) Complete(id int) error {
	i := m.indexOf(id)
	if i < 0 {
		return fmt.Errorf("complete task %d: %w", id, ErrNotFound)
	}
	m.tasks[i].Done = true
	return nil
}

func (m *TaskManager) Remove(id int) error {
	i := m.indexOf(id)
	if i < 0 {
		return fmt.Errorf("remove task %d: %w", id, ErrNotFound)
	}
	m.tasks = slices.Delete(m.tasks, i, i+1)
	return nil
}

func (m *TaskManager) List() {
	for _, t := range m.tasks {
		status := "[ ]"
		if t.Done {
			status = "[x]"
		}
		fmt.Printf("  %s %d. %s\n", status, t.ID, t.Title)
	}
}

func execute(m *TaskManager, line string) error {
	cmd, arg, _ := strings.Cut(strings.TrimSpace(line), " ")
	switch cmd {
	case "add":
		t, err := m.Add(arg)
		if err != nil {
			return fmt.Errorf("add: %w", err)
		}
		fmt.Printf("  added #%d\n", t.ID)
		return nil
	case "done", "rm":
		id, err := strconv.Atoi(arg)
		if err != nil {
			return fmt.Errorf("%s: %q is not a task ID", cmd, arg)
		}
		if cmd == "done" {
			return m.Complete(id)
		}
		return m.Remove(id)
	case "list":
		m.List()
		return nil
	default:
		return fmt.Errorf("%w: %q", ErrUnknownCommand, cmd)
	}
}

func main() {
	script := []string{
		"add Buy milk",
		"add Call the bank",
		"add",
		"done 1",
		"rm two",
		"rm 7",
		"edit 2",
		"list",
	}
	m := &TaskManager{}
	for _, line := range script {
		fmt.Println(">", line)
		if err := execute(m, line); err != nil {
			fmt.Println("  error:", err)
		}
	}
}

Quick quiz 1 / 3

Given err := fmt.Errorf("remove task %d: %w", 5, ErrNotFound), what do err == ErrNotFound and errors.Is(err, ErrNotFound) return?

Quick quiz 2 / 3

With func (m TaskManager) Add(title string) (a value receiver), what does m.List() show after m.Add("A")?

Quick quiz 3 / 3

If IDs came from len(m.tasks)+1: add tasks 1 and 2, call Remove(1), then Add("C"). What ID does C get?

What to remember

  • Keep the state in one struct such as TaskManager and change it only through methods
  • Methods that change state need a pointer receiver (*TaskManager)
  • Hand out IDs from an ever-increasing nextID counter, not len+1
  • Wrap sentinel errors with %w and check them with errors.Is

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project: Task Manager (Part 2) - Methods & Error Handling | Thuta Learning