Skip to content

Go is the language this curriculum reaches for when a service has to be simple to read, cheap to run, and correct under concurrency. Its design is deliberately small: a garbage collector so you never write free, structural interfaces so types satisfy contracts without declaring it, goroutines and channels so concurrent code reads like sequential code, and explicit error values so every failure path is visible in the source. The exercises in this chapter are chosen to make you lean on each of those choices until you can say why Go made it.

Concepts from other sections (7)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

The chapter is a set of exercise briefs rather than worked solutions. Each brief names a classic system to build and the language features it forces you to use. Several of them are the same problem that a section of AI Engineering or Algorithms solves in full, and for those the brief links to that section, so you can reason through your own design first and then compare it with a complete, tested one.

Learning objectives

  • Describe Go’s memory model, type system, error handling, and concurrency primitives, and say what each trades away.
  • Apply the core Go idioms (accept interfaces, return structs; explicit error checks; context propagation; defer cleanup) when designing a small system.
  • Choose between channels and sync primitives for a given concurrency problem and justify the choice.
  • Reason through the design of each exercise before reading the matching worked solution elsewhere in the books.

You should be comfortable writing a small Go program, running go test, and reading a function signature with channels in it. If you are not, read Go: packages, interfaces, goroutines, channels, context, net/http, testing in Programming and Algorithms first. The concurrency exercises also assume the vocabulary of locks, condition variables, and cancellation that the systems chapters of the books build up.

Go manages memory with a garbage collector. Values are stack-allocated by default, and the compiler’s escape analysis moves them to the heap only when a reference outlives the function. You get pointers, but no pointer arithmetic, so the class of bugs that the C chapter spends its time on simply cannot be written.

The type system is static and structural. An interface is satisfied implicitly: any type with the right method set implements it, with no implements clause. Generics arrived in Go 1.18 and are constrained by interfaces, such as cmp.Ordered for types that support <.

Errors are ordinary values of the error interface, returned alongside results. There are no exceptions. You inspect wrapped errors with errors.Is and errors.As, and the price of that visibility is the familiar if err != nil after every call that can fail.

Concurrency is built into the language: goroutines are cheap threads scheduled by the runtime, channels pass values between them, select waits on several channel operations at once, the sync package supplies mutexes, wait groups, and sync.Once, and context.Context carries cancellation and deadlines across call chains. The toolchain is go build, go test, and go vet, with dependencies declared in go.mod. The exercises target Go 1.22 or later.

These are the habits the exercises reward. Each one is short to state and takes practice to apply well.

  • Accept interfaces, return structs. Callers can pass anything that fits, and you keep the freedom to add methods to what you return.
  • if err != nil. Check every error explicitly, at the point it happens.
  • Table-driven tests with the testing package: one slice of cases, one loop.
  • Thread context.Context through every call chain that can block or be cancelled.
  • Give channels a direction in function signatures (chan<-, <-chan) so the compiler enforces who sends and who receives.
  • Embed for composition instead of reaching for inheritance.
  • defer for cleanup. Deferred calls run in last-in, first-out order when the function returns.

The briefs are listed below, ordered by concept rather than by difficulty, so choose by the difficulty rating (1 is easiest, 5 hardest) rather than by number. Worked Go solutions for these exercises have not been written yet; where a full solution of the same problem exists elsewhere in the books, the last column links to it.

#ExerciseConceptsDifficulty (1-5)Worked elsewhere
01Concurrent web crawlerGoroutines, channels, sync.WaitGroup, rate limiting3RAG Ingest: Crawler, Chunker, Embedder, and Store
02In-memory key-value storesync.RWMutex, interfaces, HTTP handler2Response cache: LRU, TTL, singleflight, and tenant-scoped keys
03Worker poolBounded concurrency, context cancellation3The task protocol and workers
04Generic sorted setGenerics, type constraints, cmp.Ordered3Durable timers
05Log-structured storageio.Reader/Writer, binary encoding, file I/O4The append-only event log
06Pub/sub message brokerChannels, fan-out, select, graceful shutdown3The task queue
07Rate limiter (token bucket)time.Ticker, atomic operations, middleware2Rate Limiting: RPM Token Buckets and TPM Reserve/Settle
08Raft consensus (simplified)State machines, RPC, leader election5Raft high availability for the durable log
09Dependency injection containerReflection, interfaces, sync.Once3
10gRPC service and clientProtocol buffers, streaming, interceptors4The task protocol and workers

All of the linked sections are in AI Engineering, where the problem is solved as part of a larger platform rather than in isolation. Read the brief, sketch your own design, and only then open the worked version.

  • Escape analysis: a compiler pass that keeps a value on the stack unless a reference to it can outlive the function, in which case the value is moved to the heap; Go and the JVM use it to reduce garbage-collector work.
  • Errors as values: reporting failure by returning an ordinary error value alongside the result, as Go’s error interface does, instead of throwing an exception; every failure path is then an explicit check such as if err != nil.
  • Accept interfaces, return structs: the Go guideline to take parameters as small interfaces, so callers can pass anything that fits, and to return concrete types, so methods can be added later without breaking callers.
  • Table-driven test: a test written as a slice of input and expected-output cases run by one loop, so adding a case is one line; the standard style of Go’s testing package.
  • Deferred call: a function call scheduled with Go’s defer to run when the surrounding function returns; deferred calls run in last-in, first-out order, which makes them the place for cleanup.