Go chapters

Chapter 14 of 17

Modules and Packages

Try this in our Go Compiler →

Splitting code into files

As your project grows, putting everything in one file becomes a nightmare. Go lets you split code across many files (called modules) and import names from one file into another. Each module groups together a related set of functions and types.

// math/math.go
package math
func Add(a, b int) int { return a + b }

// main.go
import "myapp/math"
fmt.Println(math.Add(2, 3))

Third-party packages

You almost never need to write everything from scratch. Go has a huge ecosystem of open-source libraries — for parsing JSON, talking to databases, building web servers, doing maths, and thousands of other tasks. Use the official package manager to add and update dependencies.

Keeping dependencies under control

Each dependency you add is code written by strangers running inside your program. Read what a package actually does before you install it, prefer well-maintained projects with many users, and remove dependencies you no longer use.

Details for go

fmt.Fscan reads tokens and returns count and error. bufio.Scanner has a default token-size limit; configure its buffer for long lines or use a Reader. Local files must share the right package. Network package downloads are not implied.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on