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¶
- Try it yourself first — set the solution aside and re-implement from the prompt below.
- Run
go test ./...from this directory. - Compare with the provided solution; log differences in your day note's "Mistakes" section.
Prompts¶
- shapes: Define a
Shapeinterface (Area(),Perimeter()), implementRectangleandCircle, then writeTotalArea([]Shape)and aDescribetype switch (square is a rectangle with equal sides). Add compile-timevar _ Shape = ...assertions. - counter: Build a
Counter(Inc,Add,Reset,Value) and aStack(Push,Popcomma-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 customFieldError{Field, Err}withUnwrap.ValidateUsershould accumulate all failures witherrors.Join. Test witherrors.Is(sentinels) anderrors.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 ./....