liveBook · Manning

Chapter 2: Diving into Go

What you will learn in chapter 2 of Go in Action, Second Edition

The chapter introduces a hands-on Go project that uses a real-world-style utility to teach language fundamentals and introduce Go’s tooling.

After this chapter you will be able to

Section by section

Introduction

The chapter introduces a hands-on Go project that uses a real-world-style utility to teach language fundamentals and introduce Go’s tooling.

Key terms: Go source structure, Go language fundamentals, ecosystem of tools, format your code, manage dependencies, test code, research documentation

2.1 Goal: A program to count words

The section introduces a Go word-counting project by proposing to recreate the familiar `wc` command-line tool.

Key terms: wc, word count, text files

2.2 What you need first

This section encourages readers to code along and outlines the minimum tools and optional setup guidance for doing so.

Key terms: Go installation, built-in terminal, IDE, alternative terminal emulator, book’s website

2.2.1 A code editor

Choose a comfortable code editor for Go, add Go support if needed, and ensure the Go tools remain available from the command line.

Key terms: Go Wiki, editor plugins, IDEs, autocompletion, Go tools, command line

2.2.2 Git

This section explains why Git is useful for Go development and how to get it if it is not already installed.

Key terms: Git, revision control system, Go toolchain, dependencies, Go standard library

2.2.3 The Go toolchain

This subsection tells readers where to install Go and what the installation provides for building and testing programs.

Key terms: Go distribution, standard library, compiler, command-line tools

2.2.4 Terminal access

This section explains where to type the commands used throughout the Go project.

Key terms: terminal emulator, command prompt, terminal

2.3 Creating your project root

This section introduces the two steps for setting up a new Go project: creating a code directory and initializing it as a Go module.

Key terms: directory, Go module

2.3.1 Creating a directory

Create a project root directory for the word-count program and understand why Go projects need one.

Key terms: project root, wordcount, gobook

2.3.2 Initializing the project module

This section initializes the wordcount project as a Go module, explains the resulting go.mod file, and gives the reason modules replaced the older GOPATH workflow.

Key terms: Go modules, go command, go mod init, module name, go.mod, main module, module directive, go directive, Go toolchain, dependencies

2.4 The first iteration: Counting spaces

This section introduces a simple space counter as the first version of a word-counting program that the chapter will improve.

Key terms: spaces, words, first pass

2.4.1 Creating main.go

This subsection creates a first complete Go program in main.go that counts spaces in a text variable.

Key terms: main.go, text variable, spaces

2.4.2 Building the program with go build

This section shows how to build the first Go program into a runnable executable.

Key terms: go build, main.go, executable, wordcount

2.4.3 Running the program with go run

This subsection introduces go run as a quick way to run the word-counting program without first building it separately.

Key terms: go run, go build, go tool

2.4.4 Formatting your code with gofmt

This section introduces gofmt as Go’s standard formatter and shows how to check and apply its formatting.

Key terms: gofmt, standard formatting, gofmt -d, diff, gofmt -w

2.4.5 Package declarations

This section explains how package declarations organize Go code and why package main, together with a main function, produces a runnable program.

Key terms: packages, module, imported, package main, main function, executable

2.4.6 Import declarations

This section explains how import declarations identify packages a Go program depends on, where they belong, and why the build toolchain needs them.

Key terms: import declaration, package declaration, dependencies, build toolchain, fmt package, formatted output, import declarations, blocks of multiple imports

2.4.7 Blocks and scope

This section explains where a Go program starts and how nested blocks determine which names code can use.

Key terms: main, entry point, block, scope, visibility, identifier, package block, universe block, append, built-in types

2.4.8 Variable declaration

This section explains explicit and short variable declarations, zero values, type inference, and how short declarations can shadow variables in a new scope.

Key terms: var, int, zero value, :=, short declaration operator, type inference, short declaration, scope, shadowing, serverAddress

2.4.9 Comments

This subsection introduces Go’s comment syntax and explains why clear comment writing matters for documentation.

Key terms: line comments, block comments, Go documentation

2.4.10 Basic for loops

Introduces Go’s three-part for loop and uses it to count spaces in a string.

Key terms: for statement, three-part for loop, init statement, condition, post statement, for loop, i, numSpaces, space character, numSpaces++

2.4.11 Calling functions in other packages

Shows how to print the word-count result with a function from another package and explains which package names other code can access.

Key terms: fmt, fmt.Println, package.function, Println, identifier, exported, uppercase letter

2.5 A better way to split the string

The section shows why counting spaces gives unreliable word counts and introduces strings.Fields as a simpler way to split text into words.

Key terms: counting spaces, strings.Fields

2.5.1 Introducing package strings

Introduces the standard library strings package as a tool for manipulating strings, in contrast to fmt’s focus on printing and formatting them.

Key terms: strings package, fmt package, standard library, splitting

2.5.2 Using go doc to view package documentation

This section shows how to look up Go package documentation and why strings.Fields is useful for counting words.

Key terms: go doc, -all, documentation comments, pkg.go.dev, standard library, strings.Fields

2.5.3 Multiple imports in an import directive

This section shows how to import both fmt and strings in one directive and describes common import-grouping conventions.

Key terms: import directive, strings package, strings.Fields, standard library imports, other dependencies

2.5.4 Slices and len

This section uses strings.Fields to produce a slice of words and len to count them, while introducing slice indexing and its bounds.

Key terms: strings.Fields, []string, slice, index, len, zero-based indices, len(yourVariable) - 1

2.6 Reading from a file

This section introduces file input as the next step for a word-counting program that currently requires source edits to count a new string.

Key terms: os package, load from a file

2.6.1 Using the os package to interact with the filesystem

Introduces the os package as a cross-platform way to access the filesystem and identifies os.ReadFile as a quick way to load a file’s contents into memory.

Key terms: os package, filesystem, os.ReadFile

2.6.2 Multiple return values

This subsection introduces Go functions that return multiple values, using os.ReadFile to show the common result-then-error pattern.

Key terms: multiple return values, os.ReadFile, slice of bytes, error

2.6.3 Basic error handling and the log package

The section introduces Go’s basic error-handling pattern: check an error value, then log and exit if an error occurred.

Key terms: error value, nil, log, standard error, timestamp, os.Exit(1), exit code

2.6.4 Counting the words in the loaded file

This section shows how to count words in a loaded text file by converting its raw bytes to a string and splitting it on whitespace.

Key terms: os.ReadFile, slice of bytes, string(fileContents), strings.Fields, bytes package, bytes.Fields

2.6.5 Running the program on a file

This section shows how to run the word-count program with its expected input file and how to check its behavior when that file is missing.

Key terms: go run, words.txt, main.go, hardcode, error handling

2.7 Specifying the file

This section introduces the move from reading a fixed file to choosing a file through program arguments.

Key terms: program arguments, os package, words.txt

2.7.1 Getting program arguments from os.Args

This section shows how to get a filename supplied on the command line from Go’s os.Args.

Key terms: os package, os.Args, command, first argument

2.7.2 Avoiding a panic by using len

Shows how to prevent a panic when a program is run without a file-name argument.

Key terms: os.Args, len, panic, slice

2.7.3 Running your program with arguments

This section invites readers to run the word-count program on a chosen text file and optionally compare its result with wc.

Key terms: wordcount, wc, arguments

2.8 A more efficient method

Introduces buffered scanning as a way to count words without loading each entire file into memory.

Key terms: os.ReadFile, memory, bufio, Scanner, buffering

2.8.1 Using go doc to learn more about types

The section uses go doc to understand bufio.Scanner, then adapts its scanning loop to count words one line at a time.

Key terms: go doc, go doc -all, go doc -ex, NewScanner, Scanner, tokens, Scan, Text, Err, SplitFunc

2.8.2 Files and I/O interfaces

This section shows how an opened file can satisfy the scanner’s io.Reader requirement and explains why Go’s small I/O interfaces are useful conventions.

Key terms: io.Reader, Read, os.File, os.Open, NewScanner, io package, Reader, Writer, Seeker, Closer

2.8.3 Integrating the scanner loop

This subsection integrates a scanner loop into the word-counting program so it retains its behavior while handling files of any size.

Key terms: os.Readfile, os.Open, scanner, scanner loop

2.8.4 Function types for modifying behavior

The section shows how a function type lets bufio.Scanner change its tokenization behavior, making word counting a simple loop, and encourages using Go documentation to find such features.

Key terms: SplitFunc, function type, bufio.Scanner, bufio.ScanWords, Scanner, tokens, strings.Fields, go doc, pkg.go.dev, documentation

2.9 Reading multiple files

The section extends the word-counting program to process multiple files by looping over command-line arguments and explains how Go’s range loop supplies indexes and values.

Key terms: os.Args[1:], slice expression, range, filename, index, blank identifier, _

2.10 Summary

The chapter summary characterizes Go as a simple, compiled, statically typed language and highlights its documentation and standard library.

Where this is used later

Concepts explained in this chapter

← Chapter 1: Go is the solution Chapter 3: Primitive types and operators →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.