Thuta Learning
Go
AdvancedProgrammingBeginner

Summary & Next Step

GoLesson 2725 min

What you'll walk away with

  • Trace how structs, methods, interfaces and generics combine in one program
  • Explain the error pattern: return it, wrap it with %w, check it with errors.Is
  • Pick the right concurrency tool (channel, Mutex, atomic, WaitGroup, context) for a situation
  • Plan the next steps: the Task Manager project, the exercises and the standard library packages to learn

Explain it simply

The tutorial in plain language

Everything you have learned so far is a set of bricks. Variables and types hold data, functions and methods do the work, interfaces connect the parts, errors say what went wrong, and goroutines and channels let work happen at the same time.

This lesson adds no new bricks. It shows how to stack the ones you have into a house: one small program that reads JSON, checks the data and writes JSON back uses about nine features from earlier lessons. Then we plan where to go from here.

Problem → Why → Solution

The problem: knowing the pieces but not how they fit

You can solve each lesson's exercise, yet when you sit down to write a real program, such as 'read tasks from a JSON file, reject the bad ones, report the rest', it is hard to know where to start. Or you fall back on habits from another language: throwing errors with panic, drawing a big inheritance hierarchy, starting goroutines without deciding when they stop.

not_go_style.go
type BaseTask struct{ /* shared fields */ }        // inheritance thinking
type ValidatedTask struct{ BaseTask }                  // embedding is not "extends"

func LoadTasks(data []byte) []Task {
    var tasks []Task
    if err := json.Unmarshal(data, &tasks); err != nil {
        panic(err) // a bad file should be an error value, not a crash
    }
    for _, t := range tasks {
        go check(t) // who waits for this goroutine? nobody
    }
    return tasks
}

Why the Go way matters

Go's features are designed to work together. Because errors are values, a goroutine can hand them back through a slice or a channel. Because interfaces are implicit, new types plug in without changing existing code. Understanding these connections is what lets you write large programs simply; knowing each feature alone is not enough.

Core concept: the layers of a Go program

The first layer is data. Every variable has a zero value, so it is usable as soon as it is declared. A slice is a window onto a backing array, and append may share that array or move to a new one. A map must be created with make before you write to it. Structs group related fields, and pointers let a function change the caller's value.

The second layer is behaviour. Methods attach functions to a type, and you use a pointer receiver when the method changes the value or the struct holds a mutex. Interfaces are satisfied implicitly: Task in the capstone never says it implements Validator, yet it does, because it has a Validate() error method. Generics let one function serve every type that meets a constraint, as ValidateAll[T Validator] does.

The third layer is failure and concurrency. Errors are ordinary values returned last; you add context with fmt.Errorf("...: %w", err) and check them with errors.Is or errors.As instead of comparing strings. Goroutines are cheap, but each needs an owner who knows when it ends. Channels hand data over, the sync package protects shared data, and context carries the signal to stop. The last layer is tooling: gofmt, go vet and go test -race keep checking everything above.

When you need toReach for
treat many types through one behavioura small interface with one or two methods
reuse one algorithm across element typesa generic function with a constraint
tell the caller what went wrongan error value wrapped with %w
pass data from one goroutine to anothera channel
guard state many goroutines touchsync.Mutex or an atomic type
stop slow workcontext.WithTimeout or WithCancel
Think through a Go program in this order
  1. Model data with types and zero values
  2. Add behaviour: methods, interfaces
  3. Return errors; wrap them with %w
  4. Give every goroutine an owner
  5. Prove it with go test and -race

Each step makes the next one simpler: clear data shapes give clear methods, and clear error paths make concurrency easier to add.

General pattern

go
type Thing struct{ Field Type }

func (t Thing) Check() error { /* return nil or a wrapped error */ }

type Checker interface{ Check() error } // small and implicit

func CheckAll[T Checker](items []T) []error { /* one goroutine per item */ }

func main() {
    if err := load(&things); err != nil { /* report, then return */ }
    for i, err := range CheckAll(things) { /* errors.Is(err, ErrX) */ }
}

A type, a method that returns an error, a small interface describing that method, a generic function that uses the interface as a constraint, and a main that checks every error: many Go programs follow this shape.

Capstone example: validate a task file and report on it

The program below reads a JSON task list and checks each task concurrently, one goroutine per task. It rejects tasks with a bad priority, picks the unfinished ones with a generic Filter and prints a JSON report. Each line in the breakdown points back to the lesson it comes from.

capstone.go
package main

import (
    "encoding/json"
    "errors"
    "fmt"
    "sync"
)

type Task struct {
    Title    string `json:"title"`
    Priority int    `json:"priority"`
    Done     bool   `json:"done"`
}

var ErrBadPriority = errors.New("priority must be 1-3")

func (t Task) Validate() error {
    if t.Priority < 1 || t.Priority > 3 {
        return fmt.Errorf("task %q: %w", t.Title, ErrBadPriority)
    }
    return nil
}

type Validator interface {
    Validate() error
}

// ValidateAll checks every item concurrently; errs[i] belongs to items[i].
func ValidateAll[T Validator](items []T) []error {
    errs := make([]error, len(items))
    var wg sync.WaitGroup
    for i, item := range items {
        wg.Add(1)
        go func() {
            defer wg.Done()
            errs[i] = item.Validate()
        }()
    }
    wg.Wait()
    return errs
}

// Filter keeps the items for which keep returns true.
func Filter[T any](items []T, keep func(T) bool) []T {
    var out []T
    for _, item := range items {
        if keep(item) {
            out = append(out, item)
        }
    }
    return out
}

func main() {
    input := `[{"title":"write tests","priority":1},
        {"title":"refactor","priority":7},
        {"title":"deploy","priority":2,"done":true}]`

    var tasks []Task
    if err := json.Unmarshal([]byte(input), &tasks); err != nil {
        fmt.Println("bad input:", err)
        return
    }

    var valid []Task
    for i, err := range ValidateAll(tasks) {
        if errors.Is(err, ErrBadPriority) {
            fmt.Println("rejected:", err)
            continue
        }
        valid = append(valid, tasks[i])
    }

    open := Filter(valid, func(t Task) bool { return !t.Done })
    report, err := json.Marshal(map[string]any{"valid": len(valid), "open": open})
    if err != nil {
        fmt.Println("encode failed:", err)
        return
    }
    fmt.Println(string(report))
}

Code breakdown

  1. Methods and errors as valuesreturn fmt.Errorf("task %q: %w", t.Title, ErrBadPriority)

    Validate is a value-receiver method because it only reads the Task. %w wraps ErrBadPriority while adding the task's title as context (the Methods and Error Handling lessons).

  2. Generic with an interface constraintfunc ValidateAll[T Validator](items []T) []error {

    T can be any type that satisfies Validator. Task has Validate() error, so it qualifies implicitly, and ValidateAll(tasks) infers T = Task (the Interfaces and Generics lessons).

  3. One slot per goroutineerrs[i] = item.Validate()

    Each goroutine writes only its own index, so there is no race and no lock. errs is returned only after wg.Wait(), so the caller sees every write, and errs[i] always matches tasks[i] (the Goroutines and Synchronization lessons).

  4. Classify the errorif errors.Is(err, ErrBadPriority) {

    errors.Is looks for ErrBadPriority anywhere in the wrapped chain. Comparing the message string instead would break the day the wording changes.

  5. Generic helper with a function valueopen := Filter(valid, func(t Task) bool { return !t.Done })

    Filter[T any] works for any slice type, and a function value decides what to keep (the Functions, Slices and Generics lessons).

  6. JSON outreport, err := json.Marshal(map[string]any{"valid": len(valid), "open": open})

    encoding/json sorts map keys when encoding, so the output is the same on every run. The struct tags give the fields lowercase JSON names, and Marshal's error is checked rather than ignored.

You should see
rejected: task "refactor": priority must be 1-3
{"open":[{"title":"write tests","priority":1,"done":false}],"valid":2}

Where to go from here

Build the Task Manager project

The next three lessons build a Task Manager in parts, starting from structs and slices and moving on to methods, error handling and saving to a file. Type the code yourself instead of copying it, and run it.

Work through the exercise lessons

The core-basics and interfaces-and-concurrency exercises reveal the gaps left from this tutorial. When one stumps you, go back to the matching lesson.

Read the standard library

Read the documentation and examples for net/http, encoding/json, database/sql, os, io and context on pkg.go.dev. go.dev/doc/effective_go is also one of the best documents for understanding idiomatic Go.

Ship something

Write a small command-line tool or JSON API, produce one binary with go build, and run it on another machine. Finishing one complete program teaches more than reading ten lessons.

bash
gofmt -l .                  # list files whose formatting differs from gofmt
go vet ./...                # report suspicious code, such as copied locks
go test -race ./...         # run every test with the race detector
go build -o tasks .         # build one executable for this machine
GOOS=linux GOARCH=amd64 go build -o tasks-linux .   # cross-compile for Linux

In real projects

How Go is used in practice

Go is most often found in cloud infrastructure, network services and command-line tools; Docker, Kubernetes and Terraform are written in Go. Compiling to a single binary, starting fast and having concurrency built into the language make it a good fit for that work. In a typical backend service, every part of this tutorial has its place.

  • net/http handlers receive requests, decode bodies with encoding/json and check business rules on structs.
  • The database is reached through database/sql, and the request's context flows down to the query, so the query stops when the client leaves.
  • Slow jobs such as sending email or building reports run in a background worker pool, with metrics counted in atomic counters.
  • On every pull request, CI runs gofmt, go vet and go test -race ./... before a merge is allowed.

Common mistakes

Mistakes that are common right after a tutorial

Writing Go in another language's style

Common slips are using panic like an exception for ordinary failures (a missing file, bad input), treating struct embedding as inheritance and stacking layers of it, and writing a getter and setter for every field. In Go, return ordinary errors and keep panic for programmer bugs where the program truly cannot continue.

Throwing errors away with _

With data, _ := os.ReadFile(path), a missing file means the program carries on with empty data and the failure resurfaces later as a strange bug somewhere unrelated. Handle every error, or add context with %w and return it to the caller.

Goroutines with no end, and abstractions too early

Each time you write go doWork(), ask who waits for it and how it stops; with no answer, you have a goroutine leak. In the same spirit, do not add an interface or a generic while there is only one concrete type; add it when the second use appears.

Best practices

Best practices

  • Declare interfaces on the side that uses them and keep them to the fewest methods.
  • Accept interfaces and return concrete structs from functions.
  • Run gofmt on save, and go vet and go test before every commit.
  • Start each new feature from the smallest working version and grow it with tests.

Mini challenge

Mini challenge: count tasks by group

Write two generic functions. CountBy takes a slice and a function that extracts a key, and returns a map of how many items share each key. SortedKeys returns a map's keys in sorted order so the output is the same on every run. Count the tasks by priority and by done/open.

  • Write CountBy[T any, K comparable](items []T, keyOf func(T) K) map[K]int
  • SortedKeys uses the cmp.Ordered constraint and sorts with slices.Sort
  • Call CountBy with an int key (priority) and a string key (done/open)
  • Print through SortedKeys instead of ranging over the map directly
countby.go
package main

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

type Task struct {
    Title    string
    Priority int
    Done     bool
}

// CountBy groups items by the key that keyOf returns and counts each group.
func CountBy[T any, K comparable](items []T, keyOf func(T) K) map[K]int {
    // TODO: make the map, increment counts[keyOf(item)] for every item
    return nil
}

// SortedKeys returns the map's keys in ascending order.
func SortedKeys[K cmp.Ordered, V any](m map[K]V) []K {
    // TODO: collect the keys, then slices.Sort them
    return nil
}

func main() {
    tasks := []Task{
        {"write tests", 1, false},
        {"fix login bug", 1, true},
        {"update docs", 3, false},
        {"deploy", 2, true},
        {"review PR", 2, false},
    }
    // TODO: count by Priority and print "priority N: M task(s)"
    // TODO: count by "done"/"open" and print "status: M"
    fmt.Println(len(tasks), "tasks")
}

Expected: Every run prints priority 1: 2 task(s), priority 2: 2 task(s), priority 3: 1 task(s), done: 2, open: 3, in that order.

Show hint

K comparable accepts any type that can be a map key, but SortedKeys must compare with <, so it needs cmp.Ordered. Start with keys := make([]K, 0, len(m)).

Show solution
countby.go
package main

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

type Task struct {
    Title    string
    Priority int
    Done     bool
}

// CountBy groups items by the key that keyOf returns and counts each group.
func CountBy[T any, K comparable](items []T, keyOf func(T) K) map[K]int {
    counts := make(map[K]int)
    for _, item := range items {
        counts[keyOf(item)]++
    }
    return counts
}

// SortedKeys returns the map's keys in ascending order, so output is stable.
func SortedKeys[K cmp.Ordered, V any](m map[K]V) []K {
    keys := make([]K, 0, len(m))
    for k := range m {
        keys = append(keys, k)
    }
    slices.Sort(keys)
    return keys
}

func main() {
    tasks := []Task{
        {"write tests", 1, false},
        {"fix login bug", 1, true},
        {"update docs", 3, false},
        {"deploy", 2, true},
        {"review PR", 2, false},
    }

    byPriority := CountBy(tasks, func(t Task) int { return t.Priority })
    for _, p := range SortedKeys(byPriority) {
        fmt.Printf("priority %d: %d task(s)\n", p, byPriority[p])
    }

    byStatus := CountBy(tasks, func(t Task) string {
        if t.Done {
            return "done"
        }
        return "open"
    })
    for _, s := range SortedKeys(byStatus) {
        fmt.Printf("%s: %d\n", s, byStatus[s])
    }
}

Quick quiz 1 / 3

Validate is changed to return fmt.Errorf("task %q: %v", t.Title, ErrBadPriority), using %v instead of %w. What does errors.Is(err, ErrBadPriority) return?

Quick quiz 2 / 3

Task has a Validate() error method but never mentions the Validator interface. Can you call ValidateAll(tasks)?

Quick quiz 3 / 3

Why do the goroutines in ValidateAll write errs[i] instead of appending to a shared slice?

What to remember

  • A Go program is built in layers: data (types, zero values), behaviour (methods, interfaces, generics), errors, concurrency and tooling.
  • Interfaces are implicit, and generic functions can use an interface as their constraint.
  • Wrap errors with %w and check them with errors.Is; never discard them with _.
  • Every goroutine needs an owner, and shared data is protected by separate indexes, channels or sync.
  • Next: the Task Manager project, the exercises, the standard library, and shipping a program of your own.

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.

Summary & Next Step | Thuta Learning