Table of Contents
Month 2 · Week 2 — Exercises¶
Practice for encoding/json, time, context, and structured logging. Each
folder is its own package with a solution and table-driven tests. Standard
library only.
| Exercise | Concept | Day | Run tests |
|---|---|---|---|
tempjson/ |
struct tags + custom json.Marshaler/Unmarshaler round trips |
036–037 | go test ./tempjson |
humandur/ |
time.Duration arithmetic, formatting compact human strings |
038 | go test ./humandur |
retry/ |
context-aware retry: ctx first param, cancellable backoff |
040 | go test ./retry |
How to use¶
- Try it yourself first — rename 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¶
- tempjson: define a
Celsius float64whose JSON form is a quoted string like"21.5C". ImplementMarshalJSON(value receiver) andUnmarshalJSON(pointer receiver), then aReadingstruct (sensor,temp,notewithomitempty). ProvideEncode(Reading) (string, error)andDecode(string) (Reading, error). Errors must mention the offending value. - humandur: implement
Humanize(d time.Duration) stringproducing a compact2d3h4m5sform, dropping zero components, truncating sub-second precision, rendering0as"0s", and prefixing-for negative durations. - retry: implement
Do(ctx context.Context, attempts int, delay time.Duration, fn func() error) error. Returnnilon first success, the last error after exhausting attempts, andErrNoAttemptswhenattempts < 1. The backoff wait MUST select onctx.Done()so cancellation/deadline returnsctx.Err()promptly.
Results¶
| Exercise | Tests | Status |
|---|---|---|
| tempjson | TestEncode, TestDecode, TestRoundTrip, TestDecodeErrors, TestDecodeErrorMentionsValue |
✅ |
| humandur | TestHumanize |
✅ |
| retry | TestDo, TestDoStopsOnCancelledContext, TestDoHonoursDeadlineDuringBackoff |
✅ |
Tip: run all of Week 2 at once with
go test ./....