GoGo
AdvancedLesson 15 of 15

Modules, Packages & Tests – Go

Structure projects, manage dependencies and test code.

A module is a project with a go.mod (module path, Go version, dependencies). A package is a folder of .go files that share the same package line. Typical structure:

hallo/
├── go.mod            // module example.com/hallo
├── main.go           // package main
└── mathe/
    ├── mathe.go      // package mathe
    └── mathe_test.go // tests

Visibility is governed by capitalization: Add is exported, geheim is not. You import via the module path plus folder:

// mathe/mathe.go
package mathe

// Add adds two numbers.
func Add(a, b int) int { return a + b }

func geheim() {} // only visible inside mathe

// main.go
package main

import (
	"fmt"

	"example.com/hallo/mathe"
)

func main() {
	fmt.Println(mathe.Add(2, 3)) // 5
}

Tests live in *_test.go files next to the code. Test functions are named TestXyz and receive a *testing.T. The table-driven test pattern checks many cases in a loop:

// mathe/mathe_test.go
package mathe

import "testing"

func TestAdd(t *testing.T) {
	tests := []struct {
		a, b, want int
	}{
		{1, 2, 3},
		{-1, 1, 0},
		{0, 0, 0},
	}
	for _, tc := range tests {
		if got := Add(tc.a, tc.b); got != tc.want {
			t.Errorf("Add(%d, %d) = %d, expected %d", tc.a, tc.b, got, tc.want)
		}
	}
}
go test ./...           # all tests
go test -v -race ./...  # verbose, with race detector
go vet ./...            # static check for common mistakes
go get github.com/google/uuid   # add a dependency
go mod tidy             # tidy up go.mod
Tipgo.sum contains checksums of the dependencies – both files belong in version control. Subfolders named internal/ can only be imported within the module. You write benchmarks as func BenchmarkXyz(b *testing.B) and run them with go test -bench ..