Skip to content

Table of Contents

Month 1 · Week 3 — Exercises

Practice for methods, interfaces, type switches, and the Go error toolkit. Each folder is its own package with a solution and table-driven tests, using only the standard library.

Exercise Concept Day Run tests
shapes/ interfaces, implicit satisfaction, type switch 016–017 go test ./shapes
counter/ value vs pointer receivers, mutating method sets 015 go test ./counter
validate/ sentinel/custom errors, errors.Is/As/Join 018–019 go test ./validate

How to use

  1. Try it yourself first — set the solution aside and re-implement from the prompt below.
  2. Run go test ./... from this directory.
  3. Compare with the provided solution; log differences in your day note's "Mistakes" section.

Prompts

  • shapes: Define a Shape interface (Area(), Perimeter()), implement Rectangle and Circle, then write TotalArea([]Shape) and a Describe type switch (square is a rectangle with equal sides). Add compile-time var _ Shape = ... assertions.
  • counter: Build a Counter (Inc, Add, Reset, Value) and a Stack (Push, Pop comma-ok, Len). Use pointer receivers so mutation persists, and write a test proving a value copy diverges from the original.
  • validate: Create sentinel errors (ErrEmpty, ErrTooYoung) and a custom FieldError{Field, Err} with Unwrap. ValidateUser should accumulate all failures with errors.Join. Test with errors.Is (sentinels) and errors.As (extract the *FieldError).

Results

Exercise Tests Status
shapes Area, Perimeter, TotalArea, Describe ✅ pass
counter Counter, CopyDiverges, Stack ✅ pass
validate Valid, Is, As, WrappingPreservesChain ✅ pass

Tip: run all of Week 3 at once with go test ./....


Exercises