Write Go programs using functions, interfaces and concurrency primitives.

Before starting: Basic terminal use and the Go toolchain.

Practice project: Build a command-line parser with explicit errors and table-driven tests.

1. Go Foundations, Architecture & Environment

  1. Go Introduction, History & The Google Systems Philosophy
  2. Toolchain Setup, go run, go build, go env & Cross-Compilation
    Read the example and try it

    Check the target operating system and processor before choosing a release binary.

    Terminal in a Go environment.

    go env GOOS GOARCH

    Compare the target OS and architecture settings for two builds.

    Target Linux/amd64 for build A and Windows/arm64 for build B. Use GOOS and GOARCH with go build.

    Expected result
    A is a Linux x86-64 executable; B is a Windows ARM64 executable. Verify each with go version -m <file>, looking for GOOS and GOARCH rather than running it on the wrong host.
  3. Program Anatomy: Packages, Declarations, main() & Export Rules
    Read the example and try it

    An executable has a main package and an entry function. Put this complete program in main.go and run it.

    Go source fragment. Use package main, import the packages referenced below, and place executable statements inside main.

    package main
    import "fmt"
    func main() { fmt.Println("Seat 7 is ready") }

    Sort Reader and reader into exported and unexported identifiers.

    Declare package-level types Reader and reader.

    Expected result
    Reader is exported; reader is private to its package. An importing package can name pkg.Reader but cannot name pkg.reader.
  4. Variables, Zero Values, Short Declaration (:=) & Scope Rules
    Read the example and try it

    An uninitialised integer starts at zero. Assignment then replaces that value.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var seats int
        fmt.Println(seats)
        seats = 6
        fmt.Println(seats)
    }

    Print the initial values of an int and a bool.

    Declare var n int and var open bool.

    Expected result
    0 false
  5. Primitive Data Types, Runes, Bytes & Explicit Type Conversions
    Read the example and try it

    Indexing a string reads bytes. Counting runes answers how many Unicode code points it holds.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        word := "café"
        fmt.Println(len(word), len([]rune(word)))
    }

    Compare byte length and rune count for a word containing é.

    Use the single-letter string é encoded as UTF-8.

    Expected result
    2 1 — bytes then runes.

2. Operators, Control Flow & Data Structures

  1. Constants, Untyped Literals & The iota Enumerator Pattern
    Read the example and try it

    Each line of this const group advances iota. The first ticket code starts at one.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        const (
            single = iota + 1
            returnTrip
        )
        fmt.Println(single, returnTrip)
    }

    Write three constants and predict their values.

    Declare three consecutive constants starting with iota.

    Expected result
    0 1 2
  2. Operators: Arithmetic, Relational, Logical, Bitwise & Pointer Operators
    Read the example and try it

    A bit mask can record independent flags. Test a flag by checking whether its bit is present.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        const paid = 1 << 1
        flags := 6
        fmt.Println(flags & paid != 0)
    }

    Compare integer division with division after conversion to float64.

    Divide 7 by 2, then convert before division.

    Expected result
    3 3.5
  3. Conditionals: if with Initialization & Advanced switch Patterns
    Read the example and try it

    A switch can test a sequence of conditions. Only the first matching case prints a message.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        left := 2
        switch {
        case left == 0: fmt.Println("Full")
        case left < 3: fmt.Println("Nearly full")
        default: fmt.Println("Available")
        }
    }

    Trace two adjacent cases without a fallthrough statement.

    Set state to open. The open case prints start; the closed case prints stop.

    Expected result
    start
  4. The Unified for Loop: Traditional, While-Style, Infinite & Range
    Read the example and try it

    Range supplies an index and a value for each stop. The first position is zero.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        for i, stop := range []string{"Hill", "Lake"} {
            fmt.Println(i, stop)
        }
    }

    Print both the index and value from a three-item slice.

    Use []int{4,8,6}.

    Expected result
    0:4 1:8 2:6
  5. Fixed Arrays: Memory Layout, Value Semantics & Comparison
    Read the example and try it

    Assigning an array copies its entries. Editing the copy leaves the first array unchanged.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        a := [2]int{4, 6}
        b := a
        b[0] = 99
        fmt.Println(a, b)
    }

    Copy an array and edit just the copy.

    Copy [2]int{4,8} and set element zero of the copy to 9.

    Expected result
    [4 8] [9 8]

3. Slices, Maps & String Internals

  1. Slice Internals: Pointer, Length, Capacity & Sub-slicing
    Read the example and try it

    A slice can share the backing array. Editing a sliced row updates the matching element of the original.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        seats := []int{1, 2, 3}
        back := seats[1:]
        back[0] = 8
        fmt.Println(seats)
    }

    Draw two overlapping slices and trace a write.

    Use a=[1,2,3], left=a[:2], right=a[1:]. Set left[1]=7.

    Expected result
    [1 7 3] [7 3]
  2. Slice Operations: make(), append(), Growth & Three-Index Slicing
    Read the example and try it

    Length counts current elements and capacity counts available slots in the backing array. Save the slice returned by append.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        row := make([]int, 0, 3)
        row = append(row, 7)
        fmt.Println(len(row), cap(row))
    }

    Grow a slice beyond capacity and examine its returned length.

    Begin with make([]int,1,1) and append 9.

    Expected result
    1 2 true — the returned slice has length two and enough capacity. Exact growth beyond that is unspecified.
  3. Maps: Hash Tables, Key Constraints, Comma-Ok & Deletion
    Read the example and try it

    A missing map key yields a zero value. The second lookup result distinguishes a missing room from a room with zero seats.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        rooms := map[string]int{"Lab": 0}
        n, found := rooms["Hall"]
        fmt.Println(n, found)
    }

    Set one key to zero and look up it and a missing key.

    Store zero at key Lab and leave Hall absent.

    Expected result
    0 true 0 false
  4. String Internals: UTF-8, Byte Slices & The strings/strconv Packages
    Read the example and try it

    Convert numeric text with a parser and check the error. A bad label should never become a real seat count by accident.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        n, err := strconv.Atoi("12")
        fmt.Println(n, err == nil)
    }

    Compare indexing and ranging over a non-ASCII string.

    Use é. Print its first byte in decimal, then its range byte index and rune value.

    Expected result
    195 0 233
  5. Pointers: Address-of (&), Dereferencing (*), Stack vs Heap & Escape Analysis
    Read the example and try it

    A pointer refers to the existing variable. Writing through it changes the caller-visible value.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        seats := 8
        p := &seats
        *p -= 2
        fmt.Println(seats)
    }

    Return a local counter's address and read it in the caller.

    Have a function return the address of a local int initialized to 4.

    Expected result
    4

4. Functions, Error Handling & Control Patterns

  1. Functions: Signatures, Multiple Returns, Named Returns & Variadics
    Read the example and try it

    A variadic parameter collects the supplied numbers into a slice. This function can total one fare or several fares.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func total(fares ...int) int {
        n := 0
        for _, fare := range fares { n += fare }
        return n
    }
    
    func main() {
        fmt.Println(total(3, 4, 8))
    }

    Sum three numbers both individually and through a slice.

    Sum 2,3,5 and then unpack []int{2,3,5}.

    Expected result
    10 10
  2. Anonymous Functions, Closures & First-Class Function Values
    Read the example and try it

    The function value remembers the surrounding counter. Calling the same closure twice advances the same sequence.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        n := 0
        next := func() int { n++; return n }
        fmt.Println(next(), next())
    }

    Make two separate counters and compare their results.

    Initialize each counter at zero. Call A twice and B once.

    Expected result
    1 2 1
  3. The defer Statement: LIFO Order, Argument Timing & Resource Cleanup
    Read the example and try it

    Deferred calls run as the surrounding function finishes, last scheduled first. Predict the order of the two labels.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        defer fmt.Println("first")
        defer fmt.Println("second")
        fmt.Println("work")
    }

    Write three deferred prints and predict the order.

    Defer printing A, B and C in that order.

    Expected result
    C B A
  4. Idiomatic Error Handling: error Interface, Wrapping & errors.Is/As
    Read the example and try it

    Wrapping an error adds context. errors.Is can still recognise the underlying cause.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "errors"
    )
    
    func main() {
        missing := errors.New("missing seat")
        err := fmt.Errorf("booking: %w", missing)
        fmt.Println(errors.Is(err, missing))
    }

    Wrap a sentinel error and check it at the caller.

    Wrap an error named closed with %w and test errors.Is.

    Expected result
    true
  5. Exceptional Flow: panic(), recover() & When NOT to Panic
    Read the example and try it

    A deferred function in the panicking goroutine can recover. Use ordinary error returns for expected input problems.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func inspect() {
        defer func() { fmt.Println("caught:", recover()) }()
        panic("damaged fixture")
    }
    
    func main() {
        inspect()
    }

    Trace a panic through a deferred recovery function.

    Panic with the string closed and recover directly inside a deferred function.

    Expected result
    caught closed

5. Structs, Methods & Object-Oriented Patterns

  1. Structs: Declaration, Anonymous Structs, Field Tags & Memory Alignment
    Read the example and try it

    A struct groups the fields of one record. A tag tells the JSON encoder which external field name to use.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    func main() {
        type Ticket struct { Seat int `json:"seat"` }
        data, err := json.Marshal(Ticket{Seat: 5})
        fmt.Println(string(data), err)
    }

    Marshal a struct whose JSON name differs from its Go name.

    Use an exported Go field Seats with the JSON name seats and value 8.

    Expected result
    {"seats":8}
  2. Methods: Value Receivers vs Pointer Receivers & Method Sets
    Read the example and try it

    A pointer receiver can change the original object. Try reserving one place and then inspect the remaining count.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    type Room struct { Left int }
    func (r *Room) Reserve() bool {
        if r.Left == 0 { return false }
        r.Left--
        return true
    }
    
    func main() {
        r := Room{Left:1}
        fmt.Println(r.Reserve(), r.Reserve())
    }

    Compare two increment methods on the same counter.

    Start a counter at 4. Increment a copy, then increment through a pointer.

    Expected result
    4 5 — only the pointer receiver changes the original.
  3. Composition over Inheritance: Struct Embedding & Field Promotion
    Read the example and try it

    Embedding makes a field available through the outer value. The embedded value still has its own type.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        type Address struct { Gate string }
        type Ticket struct { Address; Seat int }
        t := Ticket{Address{"East"}, 7}
        fmt.Println(t.Gate, t.Seat)
    }

    Access an embedded field both explicitly and by its promoted name.

    Embed a Room containing Seats=8 in a Lab.

    Expected result
    8 8
  4. Interfaces: Implicit Implementation (Duck Typing) & Decoupling
    Read the example and try it

    An interface names the behaviour a caller needs. A value with the required method can be passed without declaring an explicit relationship.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    type Labeler interface { Label() string }
    type Seat int
    func (s Seat) Label() string { return fmt.Sprintf("Seat %d", s) }
    func display(x Labeler) { fmt.Println(x.Label()) }
    
    func main() {
        display(Seat(4))
    }

    Test a type with the required method against a small interface.

    Assign a strings.Reader holding "Hi" to io.Reader. Read one byte.

    Expected result
    H
  5. Empty Interface (any), Type Assertions, Type Switches & Reflection
    Read the example and try it

    A checked type assertion returns a value and a success flag. This protects the program when the input has another type.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var value any = "7"
        n, ok := value.(int)
        fmt.Println(n, ok)
    }

    Try a failed type assertion and inspect both returned values.

    Store integer 7 in any and assert it is a string using the comma-ok form.

    Expected result
    "" false

6. Concurrency Core: Goroutines & Channels

  1. The Go Concurrency Model: CSP Architecture & The M:N GMP Scheduler
    Read the example and try it

    Goroutines can run concurrently even with one logical processor. Communicate the result to create a clear completion point.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        done := make(chan string)
        go func() { done <- "checked" }()
        fmt.Println(<-done)
    }

    Distinguish concurrent tasks from OS threads in a diagram.

    Draw two runnable goroutines and a single available execution slot.

    Expected result
    Both goroutines may make progress by being scheduled in turn. They need no dedicated thread per goroutine. Concurrency alone does not mean simultaneous execution.
  2. Goroutines: Spawning (go func()), Dynamic Stacks & Lifecycle
    Read the example and try it

    Starting a goroutine does not wait for it. Read from a completion channel so main cannot finish before the work.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        done := make(chan struct{})
        go func() { defer close(done); fmt.Println("ticket sent") }()
        <-done
    }

    Arrange for a worker to signal completion before main exits.

    Have main receive a completion signal after a worker stores the value 7.

    Expected result
    7
  3. Channels: Unbuffered Channels, Synchronization & Deadlocks
    Read the example and try it

    An unbuffered channel transfers a value when sender and receiver are both ready. Start the sender before waiting for a value.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        score := make(chan int)
        go func() { score <- 8 }()
        fmt.Println(<-score)
    }

    Trace a send and receive in two goroutines.

    Use an unbuffered channel. A sender sends 8 and the caller receives it.

    Expected result
    8
  4. Buffered Channels, Capacity Blocking, Closing & for range Iteration
    Read the example and try it

    A buffer holds values until a reader catches up. Closing after sending allows range to finish after the buffer drains.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        jobs := make(chan int, 2)
        jobs <- 4
        jobs <- 7
        close(jobs)
        for job := range jobs { fmt.Println(job) }
    }

    Send two items, close the channel and predict loop output.

    Buffer 3 and 5 in that order, close the channel, then range over it.

    Expected result
    [3 5]
  5. Multiplexing with select: Non-blocking I/O, Timeouts & Defaults
    Read the example and try it

    A default arm makes a select nonblocking. With no buffered value ready the example reports that the queue is empty.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        q := make(chan int, 1)
        select {
        case n := <-q: fmt.Println(n)
        default: fmt.Println("empty")
        }
    }

    Explain why a test must allow either ready case.

    Prepare two channels that can both receive a send. Label their cases A and B.

    Expected result
    Either A or B is a valid single choice. A test should verify membership in {A,B}, not require both choices in any fixed number of trials.

7. Advanced Concurrency & Synchronization

  1. sync.WaitGroup: Coordinating Workers & Preventing Goroutine Leaks
    Read the example and try it

    Register work before starting it. Each worker signals when it finishes so Wait can return safely.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func main() {
        var tasks sync.WaitGroup
        tasks.Add(1)
        go func() { defer tasks.Done(); fmt.Println("packed") }()
        tasks.Wait()
    }

    Mark Add, Done and Wait on a two-worker timeline.

    Track two workers using a WaitGroup.

    Expected result
    Add(2) before launch → each worker finishes and calls Done → Wait returns. The two Done calls can arrive in either order.
  2. Mutex & RWMutex: Shared Memory, Race Conditions & -race Detector
    Read the example and try it

    Protect every access to shared mutable state with the same mutex. Read the value while the lock is held too.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func main() {
        var mu sync.Mutex
        n := 0
        add := func() { mu.Lock(); defer mu.Unlock(); n++ }
        add()
        mu.Lock(); fmt.Println(n); mu.Unlock()
    }

    Group a balance check and update under the same lock.

    Two workers each request 4 from a balance of 5; lock around check and subtraction.

    Expected result
    Final balance is 1. Exactly one withdrawal succeeds, regardless of which worker acquires the lock first.
  3. Atomic Operations: sync/atomic, Lock-Free Counters & Memory Fences
    Read the example and try it

    An atomic counter supports safe increments of a single value. More complex relationships between fields need separate coordination.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "sync/atomic"
    )
    
    func main() {
        var count atomic.Int64
        count.Add(3)
        count.Add(1)
        fmt.Println(count.Load())
    }

    Separate a counter increment from a multi-field invariant.

    Two workers add 1 to one atomic counter. A separate transfer adjusts two balances.

    Expected result
    Counter ends at 2. The transfer needs synchronization covering both balances if readers must never see half the transfer.
  4. The Worker Pool Pattern: Bounded Concurrency & Job Queues
    Read the example and try it

    A worker takes jobs until the producer closes the queue. With several workers, avoid relying on one particular completion order.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func worker(jobs <-chan int, done chan<- int) {
        for id := range jobs { done <- id * 2 }
    }
    
    func main() {
        jobs, done := make(chan int, 1), make(chan int, 1)
        jobs <- 6
        close(jobs)
        worker(jobs, done)
        fmt.Println(<-done)
    }

    Trace five jobs through two workers.

    Queue jobs 1–5, close the queue, and let two workers each compute a square.

    Expected result
    All five squares appear once: 1, 4, 9, 16, 25. Arrival order and the split between workers may vary.
  5. The context Package: Cancellation, Deadlines, Timeouts & Values
    Read the example and try it

    Cancellation closes the context's Done channel. A worker can then stop and let its caller inspect the cause.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "context"
    )
    
    func main() {
        ctx, cancel := context.WithCancel(context.Background())
        cancel()
        <-ctx.Done()
        fmt.Println(ctx.Err())
    }

    Add a cancellation case to a blocking worker loop.

    Cancel a context while an unbuffered jobs channel has no sender.

    Expected result
    canceled — the cancellation case releases the blocked worker.

8. Modern Go: Generics, Modules & Tooling

  1. Go Modules (go.mod, go.sum): Dependency Resolution & Semantic Versioning
    Read the example and try it

    A module file records the module path and dependency requirements. Inspect this information inside the project directory.

    Terminal inside a Go module.

    go list -m -json

    Find the module path and one dependency requirement in a sample.

    Read this sample go.mod: module example.org/campus; go 1.22; require example.org/rooms v1.2.0 (put each directive on its own line).

    Expected result
    Module path: example.org/campus. Required dependency: example.org/rooms at v1.2.0. Reading this sample requires no network access.
  2. Modern Generics (Go 1.18+): Type Parameters, Constraints & Type Sets
    Read the example and try it

    A comparable type constraint permits equality tests. The same function can compare two strings or two integers.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    func same[T comparable](a, b T) bool { return a == b }
    
    func main() {
        fmt.Println(same(4,4), same("A","B"))
    }

    Choose a constraint for a function comparing ordered values.

    Call a generic maximum function on 2,5 and on "Lab","Hall".

    Expected result
    5 Lab — use cmp.Ordered for the > comparison.
  3. Generic Data Structures: Type-Safe Stacks, Queues & Map Utilities
    Read the example and try it

    A generic stack can store several types without converting them to an empty interface. Appending places a new value at the end.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
    )
    
    type Stack[T any] []T
    func (s *Stack[T]) Push(v T) { *s = append(*s, v) }
    
    func main() {
        var s Stack[int]
        s.Push(4)
        s.Push(7)
        fmt.Println(s[len(s)-1])
    }

    Pop from an empty stack and from a stack containing zero.

    Pop from an empty integer stack and then from one containing zero.

    Expected result
    0 false then 0 true — the success flag distinguishes these cases.
  4. Modern Standard Library Tooling: slices, maps, cmp & go work
    Read the example and try it

    Library helpers keep common operations readable. Clone a slice before sorting it to preserve arrival order.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "slices"
    )
    
    func main() {
        ids := []int{8, 2, 5}
        sorted := slices.Clone(ids)
        slices.Sort(sorted)
        fmt.Println(ids, sorted)
    }

    Sketch a workspace that points to an app and a local library.

    Imagine ./app and ./library each contain their own go.mod.

    Expected result
    A go.work at their common parent lists use ./app and use ./library. go work edit -json should list both directory paths.
  5. Code Quality & Static Analysis: go vet, golangci-lint, fmt & Fuzzing
    Read the example and try it

    Static analysis can spot suspicious calls before the program runs. Run vet from a module directory and inspect each diagnostic.

    Terminal inside a Go module.

    go vet ./...

    Distinguish a vet diagnostic from a failing fuzz input.

    One function uses %d to format text. Another crashes only for the empty input discovered by a fuzzer.

    Expected result
    go vet can flag the mismatched format. The empty input becomes a reproducible failing fuzz case. Fix both and rerun their different checks.

9. Web Development, Networking & Serialization

  1. Standard Library HTTP Server: net/http, Handler & Request Lifecycle
    Read the example and try it

    An HTTP handler writes the response for one request. Register it on a local mux that your server serves.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httptest"
    )
    
    func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/seat", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintln(w, "A4")
        })
        w := httptest.NewRecorder()
        mux.ServeHTTP(w, httptest.NewRequest("GET", "/seat", nil))
        fmt.Print(w.Body.String())
    }

    Return a text response with a custom content type.

    Return Room open as text/plain from a test handler.

    Expected result
    Status 200, Content-Type text/plain, body Room open.
  2. Modern HTTP Routing (Go 1.22+ Enhanced ServeMux & Path Parameters)
    Read the example and try it

    With Go 1.22 or later a route pattern can capture a path value. The handler receives the selected ID through the request.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httptest"
    )
    
    func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("GET /seats/{id}", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintln(w, r.PathValue("id"))
        })
        w := httptest.NewRecorder()
        mux.ServeHTTP(w, httptest.NewRequest("GET", "/seats/17", nil))
        fmt.Print(w.Body.String())
    }

    Compare a path ID with a query filter on the same request.

    Register GET /rooms/{id} and request /rooms/7?floor=2. Requires Go 1.22 or newer.

    Expected result
    7 2 — path ID then query filter.
  3. JSON Serialization: encoding/json, Streaming, Omitempty & Custom Marshaling
    Read the example and try it

    Encoding JSON converts exported fields or map entries into bytes. Check the error before sending the bytes to a client.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    func main() {
        body, err := json.Marshal(map[string]int{"seats": 4})
        if err == nil { fmt.Println(string(body)) }
    }

    Compare marshaling an exported and an unexported field.

    Marshal a struct containing exported Name="Lab" and private secret="key".

    Expected result
    {"Name":"Lab"}
  4. RESTful API Architecture: Middleware Pipeline, CORS & Status Codes
    Read the example and try it

    Middleware wraps an existing handler. Set the response header before the wrapped handler writes the body.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httptest"
    )
    
    func mark(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("X-Study", "room")
            next.ServeHTTP(w, r)
        })
    }
    
    func main() {
        base := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "Room") })
        w := httptest.NewRecorder()
        mark(base).ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
        fmt.Println(w.Header().Get("X-Study"))
    }

    Trace a logger around a handler and identify the return path.

    Wrap a handler with logging before and after calling it once.

    Expected result
    before handler after
  5. Database Persistence: database/sql, Connection Pools & Prepared Statements
    Read the example and try it

    A sql.DB represents a pool. Inspect pool statistics on an open database when requests spend time waiting for connections.

    Go package fragment. Call report with an existing *sql.DB from your application.

    package stats
    
    import ("database/sql"; "fmt")
    
    func report(db *sql.DB) {
        stats := db.Stats()
        fmt.Println(stats.InUse, stats.WaitCount)
    }

    Separate opening a pool from beginning a transaction.

    Start with an empty table whose ID must be unique. In one transaction insert IDs 1 and 2. In another, insert 3 and then try to insert 2 again.

    Expected result
    Commit the first transaction. The duplicate 2 causes the second transaction to fail; roll it back. Reading the IDs in ascending order returns 1 and 2. Use the same transaction for both inserts and check the error from Commit.

10. Testing, Profiling, DevOps & Enterprise Go

  1. Native Testing Framework: Unit Tests, Table-Driven Tests & Subtests
    Read the example and try it

    Use named test cases for the boundary and the normal path. Put this test in a file ending in _test.go.

    Go test file. Run go test -v from the module directory.

    package main
    
    import "testing"
    
    func canReserve(left int) bool { return left > 0 }
    
    func TestSeats(t *testing.T) {
        for _, tc := range []struct { name string; left int; want bool }{
            {"full", 0, false}, {"last seat", 1, true},
        } {
            t.Run(tc.name, func(t *testing.T) {
                if got := canReserve(tc.left); got != tc.want { t.Fatalf("got %t, want %t", got, tc.want) }
            })
        }
    }

    Create success and failure cases with descriptive names.

    Test a validator accepting counts 1–6 with counts 3 and 0.

    Expected result
    valid_three passes with true and zero_rejected passes with false. A go test run should report PASS for both named cases.
  2. Performance Benchmarking: testing.B, Memory Allocations & Inlining
    Read the example and try it

    Run a benchmark repeatedly and include allocations in the report. Compare results using the same inputs and compiler settings.

    Terminal in a Go module containing benchmark functions.

    go test -bench=. -benchmem

    Compare elapsed time and allocations for two implementations.

    Benchmark two ways of building the same text using go test -bench=. -benchmem.

    Expected result
    Both functions must produce identical text first. Record ns/op and allocs/op separately. Actual measurements depend on the machine; a winner is not guaranteed.
  3. Diagnostic Profiling with pprof: CPU, Heap & Goroutine Dumps
    Read the example and try it

    A CPU profile samples where work happens. Run an existing benchmark and inspect the saved measurements.

    Terminal in a Go module containing benchmark functions.

    go test -bench=. -cpuprofile=study.cpu
    go tool pprof -top study.cpu

    Choose a CPU or heap profile for two different symptoms.

    One service pins a CPU during calculation. Another retains more live objects after each request.

    Expected result
    Calculation: examine a CPU profile's hot call stacks. Retention: compare heap profiles and live allocation sites under comparable load.
  4. Graceful Shutdown: OS Signal Handling & Kubernetes Probes
    Read the example and try it

    Give active requests time to finish when stopping an HTTP server. The timeout bounds the wait if a handler gets stuck.

    Standalone Go program. Save it as main.go and run go run main.go. Use Go 1.22 or later for these exercises.

    package main
    
    import (
        "fmt"
        "context"
        "net/http"
        "time"
    )
    
    func drain(server *http.Server) error {
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        return server.Shutdown(ctx)
    }
    
    func main() {
        fmt.Println(drain(&http.Server{}))
    }

    Plan separate steps for stopping new traffic and draining requests.

    A request is still running when the service receives a termination signal.

    Expected result
    Mark readiness false, stop accepting new work, call Shutdown with a deadline and let the accepted request finish. Close shared resources after draining.
  5. Production Containerization & DevOps: Multi-Stage Docker & scratch Images
    Read the example and try it

    The builder compiles a Go program. The final image starts empty. Copy in the executable so it can run, and copy in trusted certificate authorities so it can verify the HTTPS server.

    Save this program as main.go in an empty folder. Use a local Docker engine set to Linux containers. The build needs access to the Go base image; the running container needs DNS and HTTPS access to example.com.

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
        "time"
    )
    
    func main() {
        client := http.Client{Timeout: 30 * time.Second}
        response, err := client.Get("https://example.com/")
        if err != nil {
            log.Fatal(err)
        }
        defer response.Body.Close()
        if response.TLS == nil || len(response.TLS.VerifiedChains) == 0 {
            log.Fatal("no verified TLS certificate chain")
        }
        if response.StatusCode != http.StatusOK {
            log.Fatalf("unexpected HTTP status: %s", response.Status)
        }
        fmt.Println("HTTPS GET:", response.Status)
        fmt.Println("TLS certificate verified")
    }

    Build the image, make one HTTPS request, then run it again without usable trust roots.

    After the successful run above, try this in the same terminal: docker run --rm -e SSL_CERT_FILE=/missing.pem -e SSL_CERT_DIR=/missing study-go-https

    Expected result
    Normal run (exit 0):
    HTTPS GET: 200 OK
    TLS certificate verified
    
    With both trust paths missing, the request fails with “x509: certificate signed by unknown authority” and the process exits with code 1. The log timestamp can vary.

Trace changing state and check loop boundaries

A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.

Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.

PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
    total ← total + value
RETURN total
Check the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.

Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.

Make a small learning project reproducible

A project is reproducible when another learner can obtain the same inputs, install the required tools, and repeat your checks. Record the tool versions and exact run commands. Use synthetic or permission-cleared sample data. Keep credentials outside the repository. A successful run on your laptop is a starting point; a fresh environment is a better check.

Any language; choose the package and build tools appropriate to that course

study-project/
  README.md          # setup, run, test, expected result
  src/               # your implementation
  tests/             # behavior checks
  data/              # small synthetic example data
  .gitignore         # caches, build output, local secrets
Check the output
This is a suggested directory layout, not a command to execute. Adapt conventions to the chosen language.

Build a score summarizer. Include an empty-input test, a malformed-input test, and one example whose answer can be calculated by hand.

Open the Go learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.