Tutorials / Go: From Basics to Production / Packages and modules

Packages and modules

13 min read go
Course contents (17 lessons)
  1. Getting started with Go
  2. Installing Go 1.25 and your first program
  3. Variables, types and constants
  4. Control flow: if, for and switch
  5. Functions, multiple returns and defer
  6. Slices and maps
  7. Arrays and slices
  8. Maps and working with strings
  9. Structs, methods and interfaces
  10. Structs, methods and pointers
  11. Interfaces
  12. Errors, packages and generics
  13. Error handling the Go way
  14. Packages and modules
  15. Generics
  16. Concurrency
  17. Goroutines and channels
  18. select, timeouts and context
  19. Mutexes, sync and the race detector
  20. Testing
  21. Testing and benchmarks
  22. Building and shipping a service
  23. Building an HTTP JSON API with net/http
  24. Building and deploying a Go service

Two words that mean different things

A package is a folder of Go files that share a package name. It is the unit of code organisation. A module is a collection of packages released together, described by a go.mod file at its root. One repository usually holds one module.

A small project layout

shop/
  go.mod
  main.go
  inventory/
    inventory.go
    inventory_test.go
  internal/
    money/
      money.go

Start it with go mod init example.com/shop. The module path is the prefix for every import inside it.

Writing a package

// internal/money/money.go
package money

import "fmt"

// Paisa is an amount of money in the smallest unit.
type Paisa int64

// String formats the amount as rupees with two decimals.
func (p Paisa) String() string {
	return fmt.Sprintf("Rs %d.%02d", p/100, p%100)
}

// FromRupees converts whole and fractional rupees to Paisa.
func FromRupees(r float64) Paisa {
	return Paisa(r*100 + 0.5)
}
// inventory/inventory.go
package inventory

import (
	"errors"

	"example.com/shop/internal/money"
)

var ErrUnknownItem = errors.New("unknown item")

type Item struct {
	Name  string
	Price money.Paisa
	Stock int
}

type Inventory struct {
	items map[string]*Item
}

func New() *Inventory {
	return &Inventory{items: make(map[string]*Item)}
}

func (inv *Inventory) Add(it Item) {
	inv.items[it.Name] = &it
}

func (inv *Inventory) Price(name string) (money.Paisa, error) {
	it, ok := inv.items[name]
	if !ok {
		return 0, ErrUnknownItem
	}
	return it.Price, nil
}
// main.go
package main

import (
	"errors"
	"fmt"

	"example.com/shop/internal/money"
	"example.com/shop/inventory"
)

func main() {
	inv := inventory.New()
	inv.Add(inventory.Item{Name: "tea", Price: money.FromRupees(120.5), Stock: 10})

	price, err := inv.Price("tea")
	fmt.Println(price, err)

	_, err = inv.Price("coffee")
	if errors.Is(err, inventory.ErrUnknownItem) {
		fmt.Println("no coffee today")
	}
}

Run it with go run . from the module root. The output is:

Rs 120.50 <nil>
no coffee today

The rules that matter

One folder, one package. All files in a folder must declare the same package name. The folder name and the package name should match, apart from main. Package names are short, lowercase and singular, like money or inventory, with no underscores. Avoid vague names such as util or common, since they become dumping grounds.

Capital letters export. inventory.New is visible to main because it starts with a capital. The field items is lowercase, so only code inside the inventory package can touch it. That is how you hide implementation details.

Imports use the full path. Because the module path is example.com/shop, a package in the inventory folder is imported as example.com/shop/inventory. You call its names as inventory.New(). Do not repeat the package name in function names: inventory.New is better than inventory.NewInventory.

No import cycles. If package A imports B, then B cannot import A. The compiler rejects it with import cycle not allowed. When you hit this, it usually means something is in the wrong package. Move the shared piece to a third package, or define an interface where it is used.

The internal directory

A package under a folder named internal can only be imported by code inside the parent of that folder. Here, shop/internal/money can be used by anything in shop and below, but nobody outside the module can import it. It is the way to say "this is not part of my public API", and the compiler enforces it.

Dependencies

To use somebody else's package, import it and let Go fetch it:

go get github.com/google/uuid@latest
go mod tidy

Go adds the dependency and its version to go.mod and records cryptographic checksums in go.sum. Commit both files. Version numbers follow semantic versioning, and the proxy at proxy.golang.org caches modules so that builds are repeatable. go mod tidy removes what you no longer use and adds what is missing, and I run it before every commit. To upgrade, use go get -u ./... and then run your tests.

Version 2 and higher of a module has /v2 at the end of its path, such as example.com/lib/v2. If an import fails with a strange version error, check whether you need the suffix.

Tools and workflow

  • gofmt (or go fmt ./...) formats code. It is not optional in Go teams.
  • go vet ./... reports likely mistakes, such as wrong Printf verbs.
  • go build ./... checks that everything compiles.
  • go doc strings.Fields shows documentation in the terminal.
  • go list -m all lists all dependencies.

Common mistakes

  • Naming the module after something you do not own. It works locally, but the module cannot be fetched by others. Use a repository path if you plan to publish.
  • Putting everything in main. A package named main cannot be imported. Keep main thin and move logic into packages that can be tested.
  • Too many tiny packages. Splitting early causes import cycles. Start with fewer packages, and split when a clear boundary appears.
  • Forgetting to commit go.sum. Other developers then see checksum errors.

Try it yourself

Create a module with a package mathx that contains a function Average(values []float64) (float64, error), which returns an error for an empty slice. Import it from main. Then add a lowercase helper function inside mathx and try calling it from main to see the compiler's message. Finally move mathx under internal/ and make sure the program still builds.

go
// main.go
package main

import (
	"errors"
	"fmt"

	"example.com/shop/internal/money"
	"example.com/shop/inventory"
)

func main() {
	inv := inventory.New()
	inv.Add(inventory.Item{Name: "tea", Price: money.FromRupees(120.5), Stock: 10})

	price, err := inv.Price("tea")
	fmt.Println(price, err)

	_, err = inv.Price("coffee")
	if errors.Is(err, inventory.ErrUnknownItem) {
		fmt.Println("no coffee today")
	}
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account