Skip to content

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

  1. Try it yourself first — rename 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

  • tempjson: define a Celsius float64 whose JSON form is a quoted string like "21.5C". Implement MarshalJSON (value receiver) and UnmarshalJSON (pointer receiver), then a Reading struct (sensor, temp, note with omitempty). Provide Encode(Reading) (string, error) and Decode(string) (Reading, error). Errors must mention the offending value.
  • humandur: implement Humanize(d time.Duration) string producing a compact 2d3h4m5s form, dropping zero components, truncating sub-second precision, rendering 0 as "0s", and prefixing - for negative durations.
  • retry: implement Do(ctx context.Context, attempts int, delay time.Duration, fn func() error) error. Return nil on first success, the last error after exhausting attempts, and ErrNoAttempts when attempts < 1. The backoff wait MUST select on ctx.Done() so cancellation/deadline returns ctx.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 ./....


Exercises