Day 1 – Go Toolchain and CLI
Today's Focus
Set up Go toolchain, understand Go's package model, and build a working CLI utility.
Tasks
- Install Go via the official installer. Run
go versionandgo env GOPATH. Initialise a new module:go mod init github.com/yourname/week5-go. - Write a
main.gothat implements a CLI tool: a word frequency counter that reads a text file (path passed as a command-line argument usingos.Args), counts word occurrences, and prints the top 10 words sorted by frequency. - Define a
structforWordCount { Word string; Count int }and a functionTopN(counts map[string]int, n int) []WordCount. Keep business logic out ofmain(). - Handle errors explicitly:
os.Openreturns an error — check it, print a useful message toos.Stderr, and callos.Exit(1). Do not usepanicfor expected errors. - Split your code into two files:
main.go(entry point) andwordcount.go(logic). Both should be inpackage main. Rungo build ./...andgo vet ./...— fix any issues. - Write two test functions in
wordcount_test.gousing thetestingpackage. Run them withgo test -v ./....
Reading / Reference
- A Tour of Go — Basics section: packages, variables, functions, flow control, structs.
- Go docs: Effective Go — Names, Control structures, Functions, and Data sections.
- Go by Example — Command-Line Arguments, Structs, Maps, Sorting.