Lesson 3 / 26

Modules and Packages

Organising code and dependencies.

go.mod, imports and visibility

A module is a collection of packages with a go.mod file that declares its path, the Go version, and dependencies (with exact versions recorded in go.sum). A package is a directory of .go files sharing a package name; you import it by module path plus directory. Identifiers starting with an uppercase letter are exported (visible to other packages); lowercase ones are private to the package. go get adds dependencies and go mod tidy cleans them up.

A small module layout

Typical structure; names are examples.

shop/
  go.mod                 module example.com/shop
  go.sum                 checksums of dependencies
  cmd/shop/main.go       package main: wires things together
  internal/orders/       package orders: only importable inside this module
    orders.go            func New(...) *Service   (exported: capital N)
    store.go             func validate(...)       (unexported)
  internal/orders/orders_test.go

Use internal/ for private packages

Packages under internal/ cannot be imported by other modules, which keeps your public API small.

Quick check: How is an identifier exported from a Go package?

  • By putting it in main.go
  • With the export keyword
  • By listing it in go.mod
  • By starting its name with an uppercase letter
Answer

By starting its name with an uppercase letter — Capitalisation controls visibility.