Packages & Modules

Package organization, visibility rules, go.mod, and dependency management.

Intermediate 30 min read 🐹 Go

Go Packages

Every Go file belongs to a package. Packages are the unit of code organization and reuse. The naming convention is simple: package name = directory name, lowercase, no underscores.

// File: mathutil/calc.go
package mathutil

// Exported (uppercase) - accessible from other packages
func Add(a, b int) int { return a + b }

// Unexported (lowercase) - private to this package
func helper() int { return 42 }
Key Takeaway: Uppercase = exported (public). Lowercase = unexported (private to package). This is Go's only visibility mechanism — no public/private/protected keywords.

Go Modules

# Initialize a new module
go mod init github.com/yourname/myproject

# Add dependencies (auto-detected from imports)
go mod tidy

# Download dependencies
go mod download

# View dependency graph
go mod graph

Essential Standard Library

PackagePurpose
fmtFormatted I/O (Printf, Println, Sprintf)
stringsString manipulation
strconvString/number conversion
osOS functions, env vars, files
ioI/O primitives (Reader, Writer)
net/httpHTTP client and server
encoding/jsonJSON marshal/unmarshal
syncMutex, WaitGroup, Once
contextCancellation and deadlines
testingUnit testing and benchmarks

Practice Exercises

Medium Build a Mini Project

Combine concepts from this tutorial to build a small utility or tool.

Medium Debug Challenge

Introduce a bug in one of the code examples and practice finding and fixing it.

Hard Refactoring Exercise

Rewrite one example using a different approach and compare the tradeoffs.