Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

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.

Course Home

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 like encoding/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, checking if err != nil before 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 mathutil vs. package mathutil_test: Putting tests in package mathutil lets you test unexported helpers; putting tests in package mathutil_test forces your tests to import mathutil just like an external user, proving your exported API is ergonomic.

Common mistakes

  • Forgetting the Test prefix or capital letter: func testClamp(t *testing.T) compiles quietly and is completely skipped by go 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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.