Packages, Exports, and go test
Organize code into packages using capitalized exports and write table-driven unit tests with testing.T. After this, you can structure a multi-file Go module and verify changes with go test.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Why Go Exists and When to Pick It
-
Run Your First Go Program
-
-
-
Values, Control Flow, and Functions
-
Variables, Types, and Zero Values
-
If, For Loops, and Multiple Return Values
-
-
-
Slices, Maps, and Structs
-
Arrays, Slices, and Why append Matters
-
Maps, Structs, and Pointer Receivers
-
-
-
Errors, Packages, and Testing
-
Handle Errors Without Hiding Them
-
Packages, Exports, and go test
-
-
-
Files, JSON, and a Small HTTP Server
-
Read Files and Decode JSON Structs
-
Build and Test a Small net/http Server
-
-
-
Pointers, Modules, and CLIs
-
Pointers and Memory Basics
-
Managing Dependencies and internal/ Packages
-
Building CLIs With flag, os.Getenv, and Exit Codes
-
-
In Go, every directory of .go files is a package, visibility is controlled by one capitalization rule instead of public/private keywords, and unit testing ships directly inside go test—no Jest, pytest, or JUnit install required. Learning how packages and table-driven tests fit together is what turns a single script into maintainable production code.
Skip ahead
If you already organize code into packages, know exported vs. unexported identifiers, and write table-driven tests with t.Run, take the section quiz or move on to "Read Files and Decode JSON Structs."
Experiment 1: Uppercase is exported, lowercase is package-private
Go has only two visibility levels, and both depend purely on the first letter of the name:
- Starts with an uppercase letter (
Clamp,User.Name): Exported—callable from any package that imports yours (and visible to reflection packages likeencoding/json). - Starts with a lowercase letter (
defaultMin,user.secret): Unexported—visible only to files in the exact same directory and package.
// mathutil/clamp.go
package mathutil
func Clamp(n, minVal, maxVal int) int {
if n < minVal {
return minVal
}
if n > maxVal {
return maxVal
}
return n
}
func isValidRange(minVal, maxVal int) bool {
return minVal <= maxVal
}
Any file outside mathutil/ can call mathutil.Clamp(...), but trying to call mathutil.isValidRange(0, 10) fails immediately at compile time with cannot refer to unexported name mathutil.isValidRange.
Experiment 2: Your first unit test in *_test.go
Any file ending in _test.go is ignored by go build and compiled only when you run go test. A test function starts with Test and accepts t *testing.T. Instead of copy-pasting five nearly identical test functions, Go developers group test cases into a slice of structs and run each case as a named subtest with t.Run:
// mathutil/clamp_test.go
package mathutil
import "testing"
func TestClamp(t *testing.T) {
cases := []struct {
name string
in int
want int
}{
{name: "below_min", in: -5, want: 0},
{name: "inside_range", in: 42, want: 42},
{name: "above_max", in: 150, want: 100},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := Clamp(tc.in, 0, 100)
if got != tc.want {
t.Fatalf("Clamp(%d) = %d, want %d", tc.in, got, tc.want)
}
})
}
}
$ go test -v ./...
=== RUN TestClamp
=== RUN TestClamp/below_min
=== RUN TestClamp/inside_range
=== RUN TestClamp/above_max
--- PASS: TestClamp (0.00s)
PASS
ok example.com/demo/mathutil 0.002s
Experiment 3: Running one subtest and bypassing the test cache
Two go test flags save huge amounts of time once your suite grows:
# Run only one failing subtest by regex:
$ go test -v -run TestClamp/below_min ./...
# Bypass Go's passing-test cache (useful for timing/randomness checks):
$ go test -count=1 ./...
# Check statement coverage per function:
$ go test -cover ./...
Because Go caches passing test results automatically when neither your code nor test inputs changed, running go test ./... across a 50-package repository only re-executes the packages you actually touched—making feedback nearly instant.
Experiment 4: t.Fatalf vs. t.Errorf and black-box tests
Knowing when to stop a test immediately versus keeping going prevents noisy crash traces:
t.Fatalf(...): Fails the current subtest and exits it immediately. Use it whenever later lines would panic or make no sense (for example, checkingif err != nilbefore reading a parsed struct).t.Errorf(...): Records a failure and keeps executing remaining checks—great when verifying several independent fields of a struct at once.package mathutilvs.package mathutil_test: Putting tests inpackage mathutillets you test unexported helpers; putting tests inpackage mathutil_testforces your tests to importmathutiljust like an external user, proving your exported API is ergonomic.
Common mistakes
- Forgetting the
Testprefix or capital letter:func testClamp(t *testing.T)compiles quietly and is completely skipped bygo test. - Leaving out descriptive failure messages: Writing
t.Fail()tells you something broke without telling you what it got vs. what it expected. Always print"Func(%v) = %v, want %v". - Reaching for a heavy assertion library too soon: Plain
if got != want { t.Fatalf(...) }keeps test failures crystal clear and avoids hiding test intent behind magic macros.
💡 Tip
Always run go test -race ./... in CI (and locally whenever your code starts goroutines). Go's built-in race detector catches concurrent memory bugs that normal tests miss.
What happens if you skip this step
Without table-driven subtests and clear package boundaries, every bug fix becomes a risky manual check and internal helpers accidentally leak into public APIs that callers begin depending on.
You add a test function named func clampWorks(t *testing.T) inside clamp_test.go, run go test ./..., and it passes even though the assertion is intentionally wrong. Why didn't it fail?
About
Organize code into packages using capitalized exports and write table-driven unit tests with testing.T. After this, you can structure a multi-file Go module and verify changes with go test.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.