Day 2 – Go Interfaces and Concurrency
Today's Focus
Explore Go interfaces, concurrency primitives, and Go modules with external dependencies.
Tasks
- Define a
Formatterinterface with aFormat(counts []WordCount) stringmethod. Implement two structs that satisfy it:PlainFormatter(plain text table) andJSONFormatter(JSON output). Yourmain.goshould accept a--formatflag and select the right implementation. - Write a concurrent version of the file reader: use
goroutinesand achannelto process multiple files in parallel (pass multiple file paths as arguments). Use async.WaitGroupto wait for all goroutines to complete before printing results. - Add an external dependency:
go get github.com/spf13/cobra(orgithub.com/urfave/cli/v2). Refactor your CLI to use it for argument parsing and help text. Rungo mod tidyand inspectgo.modandgo.sum. - Understand
go.sum: find your new dependency's hash ingo.sum. Explain in a comment whygo.sumis committed to version control but should never be hand-edited. - Run
go list -m allto see the full dependency graph. Identify a transitive dependency you did not add directly. - Add
go generatesupport: add a comment//go:generate go fmt ./...and rungo generate ./.... Discuss whatgo generateis typically used for in larger projects.
Reading / Reference
- A Tour of Go — Interfaces and Concurrency sections.
- Go docs: Go Modules Reference — the module file, go.sum, and
go mod tidy. - Go by Example — Goroutines, Channels, WaitGroups, Interfaces.