Thuta Learning
Go
AdvancedProgrammingBeginner

Packages, Modules & Go Tooling

GoLesson 1835 min

What you'll walk away with

  • Explain the one-directory-one-package rule and the special role of package main
  • Choose between exported identifiers (capital first letter) and unexported ones visible only inside the package
  • Read the module path, go directive and require lines of go.mod, and say what go.sum protects
  • Predict the order in which package-level variables, init() and main() run
  • Use gofmt, go vet, go test and go mod tidy as the daily loop of a project

Explain it simply

Packages, modules and tooling in plain language

A package is a set of .go files that live in one directory and declare the same package name. A module is a whole tree of packages with a go.mod file at its root. go.mod declares the module's name, which is also its import path, and records the exact versions of the dependencies it uses.

Picture a building. Each package is a room, and outsiders only see the names written on the door, the ones that start with a capital letter. The module is the whole building with a street address, and go.mod is that address plus the list of suppliers. The go command is the building manager: one tool builds, tests, formats and manages dependencies.

Problem → Why → Solution

The problem: when one main.go keeps growing

A small project starts as one main.go. A few months later that file has passed two thousand lines and mixes HTTP handlers, database code and validation. You want to write tests, but nobody can tell which function depends on what. The day you split the code into packages, compile errors like the one below appear at once, and a teammate's machine builds with a different dependency version than yours.

cmd/api/main.go
package main

import "example.com/taskapi/tasks"

func main() {
	t := tasks.newTask("demo") // undefined: tasks.newTask (not exported)
	t.tags = nil                // t.tags undefined (unexported field)
}

Why Go makes the boundaries strict

Go has no public or private keywords; the first letter of an identifier decides its visibility. newTask starts with a lowercase letter, so code outside package tasks cannot call it, and that is not a bug but the door that protects the package's API. go.mod and go.sum work in the same spirit: they guarantee that every machine builds with the same dependency versions and the same content.

Core concept: packages, visibility, modules and initialization

Every .go file starts with a package clause, and all files in one directory must use the same package name (apart from an external _test package). The directory is the unit of compilation, so a function in one file can call a function in another file of the same directory without any import. A package named main with a func main() becomes an executable; any other package name is a library.

Visibility is decided by a single character: the first letter of the name. Names such as Task, NewTask and Title start with a capital letter, so they are exported and an importing package can use them as tasks.Task. Names such as newTask and tags start lowercase, so they are unexported and visible only inside the package. The rule covers types, functions, variables, constants, methods and struct fields, and reflection-based packages such as encoding/json cannot see unexported fields either.

The root of a module holds go.mod. Its module line sets the prefix of every import path, and a package's import path is the module path joined with its directory: the tasks directory inside module example.com/taskapi is imported as example.com/taskapi/tasks. The go directive states the minimum Go version the module needs, and require lines pin dependency versions. go.sum stores a cryptographic hash for each downloaded module version, so the go command refuses content that changed under the same version.

File / directoryRole
go.modmodule path, minimum Go version, dependency versions
go.sumchecksums of dependency content; commit it
internal/importable only by code under its parent directory
cmd/<name>/one package main per executable

When a program starts, Go initializes packages in a fixed order. Imported packages finish first. Inside one package, package-level variables are initialized in dependency order, then the init() functions run, and only after that does main() start. You cannot call init() yourself and it cannot return an error, so keep it for small work that cannot fail, such as filling a registry.

See a module as layers
  1. One directory = one package
  2. Capital = exported, lowercase = private
  3. go.mod declares the module path
  4. Import path = module path + directory
  5. Runs var -> init() -> main()

When an import fails or a name is undefined, check the first letter and the import path before anything else.

General pattern

go
// go.mod at the module root
module example.com/project

go 1.24

// any .go file in the directory store/
package store

import "example.com/project/internal/util"

func Exported() {} // usable elsewhere as store.Exported
func helper()   {} // usable only inside package store

go.mod declares the module path once. Each directory is a package, and its import path is the module path plus the directory. A capital first letter makes a name visible to other packages; a lowercase one keeps it inside the package.

Worked example: the export rule and initialization order

The program below is a single file, but it shows the shape of a package API: an exported type Task, an exported constructor NewTask, an unexported field tags and an unexported helper normalise. In a real project Task and NewTask would live in package tasks, and main would call tasks.NewTask. The numbered print lines also reveal the order in which the package variable, init() and main() run.

main.go
package main

import (
	"fmt"
	"sort"
	"strings"
)

// Package-level variables are initialised before any init function runs.
var defaultTags = loadDefaults()

func loadDefaults() []string {
	fmt.Println("1. package variable initialised")
	return []string{"modules", "go"}
}

func init() {
	fmt.Println("2. init runs before main")
	defaultTags = append(defaultTags, "tooling")
}

// Task is exported: another package could write tasks.Task.
type Task struct {
	Title string   // exported field
	tags  []string // unexported field: only this package can touch it
}

// NewTask is the exported constructor that fills the unexported field.
func NewTask(title string) Task {
	return Task{Title: title, tags: normalise(defaultTags)}
}

// normalise is unexported: an internal helper of this package.
func normalise(in []string) []string {
	out := make([]string, len(in))
	for i, t := range in {
		out[i] = strings.ToUpper(t)
	}
	sort.Strings(out)
	return out
}

func main() {
	fmt.Println("3. main starts")
	t := NewTask("write docs")
	fmt.Println(t.Title, t.tags)
}

Code breakdown

  1. Package variable firstvar defaultTags = loadDefaults()

    Package-level variables are initialized before any init() runs, which is why the print inside loadDefaults is the first line of output.

  2. init runs nextfunc init() {

    init() runs automatically after the variables are ready and before main(). Here it appends one more default tag; nobody calls it explicitly.

  3. Exported vs unexported fieldstags []string // unexported field: only this package can touch it

    Title is exported and tags is not. Code outside the package could read task.Title but never touch task.tags, which is why NewTask is needed to fill it.

  4. Exported constructorfunc NewTask(title string) Task {

    NewXxx is the Go naming convention for a constructor. It is the one sanctioned way to build a Task with its unexported fields set correctly.

  5. Standard library packagessort.Strings(out)

    strings and sort are standard-library packages, so they need no require line in go.mod. ToUpper and Strings start with a capital letter because they are exported, and you call them through the package name.

You should see
1. package variable initialised
2. init runs before main
3. main starts
write docs [GO MODULES TOOLING]

Laying out a module on disk

Split into packages, the example above turns into a layout like this. Each executable gets its own package main under cmd/, and shared logic moves into library packages such as tasks. Packages under internal/ cannot be imported by projects outside the module, which makes it the right home for code you do not want to promise as an API.

text
taskapi module layout
---------------------
taskapi/
|-- go.mod              module example.com/taskapi
|-- go.sum              checksums of every dependency
|-- cmd/
|   `-- api/
|       `-- main.go     package main  -> the executable
|-- internal/
|   `-- store/
|       `-- store.go    package store (only taskapi may import it)
`-- tasks/
    |-- task.go         package tasks
    `-- task_test.go    package tasks (run by go test)
tasks/task.go + cmd/api/main.go
// ---- tasks/task.go ----
package tasks

type Task struct {
	Title string
	tags  []string
}

func NewTask(title string) Task { return Task{Title: title} }

// ---- cmd/api/main.go ----
package main

import (
	"fmt"

	"example.com/taskapi/tasks"
)

func main() {
	t := tasks.NewTask("write docs") // exported: allowed
	fmt.Println(t.Title)              // exported field: allowed
}
go.mod
module example.com/taskapi

go 1.24

require github.com/google/uuid v1.6.0

The go directive is a minimum version

Since Go 1.21 the go line is the minimum Go version needed to build the module. An older toolchain may refuse a module that asks for a newer version, and with the default GOTOOLCHAIN=auto setting the go command downloads the required toolchain instead. Write the version your code really needs, not a guess.

The everyday command loop

The strength of Go tooling is that it all ships inside the go command, with no plugins to install. ./... means every package below the current directory. Make format, vet and test a habit before each commit and far fewer CI runs will fail.

bash
go mod init example.com/taskapi       # create go.mod
go get github.com/google/uuid@v1.6.0  # add or change a dependency
go mod tidy                           # add missing, drop unused requirements
gofmt -l .                            # list files that are not formatted
gofmt -w .                            # rewrite them in the standard format
go vet ./...                          # report suspicious code
go test ./...                         # run the tests of every package
go build ./...                        # compile everything
go run ./cmd/api                      # build and run one main package
CommandWhat it catches
gofmt -l .unformatted files, so reviews never argue about spacing
go vet ./...code that compiles but is wrong, e.g. bad Printf verbs or copied locks
go mod tidygo.mod and go.sum out of sync with the real imports
go test -race ./...data races between goroutines (covered in the concurrency lessons)

In real projects

How real projects use this

Most production Go services follow the same shape: executables under cmd/, private packages under internal/, and go.mod plus go.sum at the root. Teams always commit go.sum, and CI runs the same commands developers run locally.

  • CI pipelines fail the build when gofmt -l . prints any file, and run go vet ./... and go test -race ./... on every pull request.
  • Dependency updates: bots such as Dependabot open pull requests that bump require lines in go.mod, and reviewers can inspect the matching go.sum changes.
  • Private modules: for internal company repositories, teams set GOPRIVATE so module paths are not sent to the public checksum database.
  • Security scanning: the Go team's govulncheck tool reports known vulnerabilities in the code paths your module actually calls.

Common mistakes

Common mistakes with packages and modules

Keeping lowercase names after splitting a package

While everything lives in one file, a name like newTask works fine; split the package and you get undefined: tasks.newTask. The opposite reflex is also a mistake: capitalising everything lets outside code depend on internal details that you then cannot change. Export only what you want to be the API.

Creating an import cycle

If package tasks imports store and store imports tasks, Go refuses to compile with import cycle not allowed. Move the shared type into a third package, or declare a small interface on the consuming side so the dependency points one way only.

Editing go.mod by hand and forgetting go.sum

Changing a require line by hand without updating go.sum ends in a missing go.sum entry error. Use go get or go mod tidy, commit both files together, and never put go.sum in .gitignore.

Doing heavy work in init()

Connecting to a database or calling the network in init() slows every test that imports the package, and since init() cannot return an error, a failure can only panic or call log.Fatal. Put that setup in an ordinary function that main calls.

Best practices

Best practices

  • Give packages short, lowercase names without underscores (tasks, store), so call sites read like tasks.New.
  • Split packages by responsibility (tasks, billing), not by layer (models, utils).
  • Keep code you do not want to promise outside the module under internal/.
  • Set your editor to run gofmt (or goimports) on every save.

Mini challenge

Mini challenge: a formatter registry

Write, in one file, a small package-style formatter registry that is filled in init(). The registry itself must stay unexported; callers use it only through exported functions.

  • Declare an exported sentinel error ErrUnknownFormat
  • Fill an unexported registry map in init() with three formatters: upper, lower and trim
  • Names() returns the names sorted (never trust map iteration order)
  • Format(name, s) returns ErrUnknownFormat wrapped with %w for an unknown name
formats.go
package main

import (
	"errors"
	"fmt"
	"sort"
	"strings"
)

// TODO: exported sentinel error ErrUnknownFormat

// TODO: unexported registry: map from name to func(string) string

// TODO: init() registers "upper", "lower" and "trim"
//       (strings.ToUpper, strings.ToLower, strings.TrimSpace)

// Names returns the registered names in sorted order.
func Names() []string {
	// TODO: collect the map keys, then sort them
	return nil
}

// Format applies the named formatter to s.
func Format(name, s string) (string, error) {
	// TODO: look the name up; wrap ErrUnknownFormat with %w if it is missing
	return "", nil
}

func main() {
	// TODO: print Names(), Format("upper", "go modules"),
	//       and whether an unknown name matches ErrUnknownFormat
}

Expected: It prints formats: [lower trim upper], then GO MODULES. For the unknown name reverse it prints format "reverse": unknown format and unknown? true.

Show hint

Map iteration order can change between runs, so collect the keys into a slice and sort it with sort.Strings. Wrap the error with fmt.Errorf("format %q: %w", name, ErrUnknownFormat) so errors.Is can still recognise it.

Show solution
formats.go
package main

import (
	"errors"
	"fmt"
	"sort"
	"strings"
)

// ErrUnknownFormat is exported so callers can test for it with errors.Is.
var ErrUnknownFormat = errors.New("unknown format")

// registry is unexported: callers go through Names and Format.
var registry = map[string]func(string) string{}

func register(name string, fn func(string) string) {
	registry[name] = fn
}

func init() {
	register("upper", strings.ToUpper)
	register("lower", strings.ToLower)
	register("trim", strings.TrimSpace)
}

// Names returns the registered format names in a stable order.
func Names() []string {
	names := make([]string, 0, len(registry))
	for name := range registry {
		names = append(names, name)
	}
	sort.Strings(names)
	return names
}

// Format applies the named formatter to s.
func Format(name, s string) (string, error) {
	fn, ok := registry[name]
	if !ok {
		return "", fmt.Errorf("format %q: %w", name, ErrUnknownFormat)
	}
	return fn(s), nil
}

func main() {
	fmt.Println("formats:", Names())

	out, err := Format("upper", "go modules")
	fmt.Println(out, err)

	_, err = Format("reverse", "go")
	fmt.Println(err)
	fmt.Println("unknown?", errors.Is(err, ErrUnknownFormat))
}

Quick quiz 1 / 3

One file has var x = f() (f prints "var"), an init() that prints "init" and a main() that prints "main". What is the output order?

Quick quiz 2 / 3

Package tasks has type Task struct { Title string; tags []string }, func NewTask(...) Task and func newID() int. Which can package main use?

Quick quiz 3 / 3

You deleted the last import of a third-party package. Which command brings go.mod and go.sum back in line with the code?

What to remember

  • A directory is a package, and package main with func main() makes an executable.
  • A capital first letter exports a name; lowercase keeps it inside the package, fields and methods included.
  • go.mod records the module path, minimum Go version and dependency versions; go.sum protects their content with checksums.
  • Package variables initialize first, then init(), then main().
  • Run gofmt, go vet, go test and go mod tidy before each commit and in CI.

Create a Go module — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Packages, Modules & Go Tooling | Thuta Learning