Skip to content

Go modules and packages

In Go, code organization is primarily managed through packages and modules^[readme.md].

Packages

A package consists of source files located in the same directory that are compiled together^[readme.md]. All source files within a single package share visibility, meaning they can access each other's unexported identifiers^[readme.md].

Modules

A module is a collection of related Go packages that are released, versioned, and distributed together^[readme.md].

Module Structure

A repository can contain one or more Go modules, although it is standard practice to maintain a single module at the root of the repository^[readme.md].

The go.mod File

The definition of a module is contained in a go.mod file^[readme.md]. This file serves two primary purposes:

  1. Declaration: It declares the module path, which serves as the import path for the packages contained within the module^[readme.md].
  2. Dependency Management: It specifies where the module's dependencies should be downloaded from^[readme.md].

Module Paths

The module path acts as a unique identifier for the code^[readme.md]. When a program defines a module path, it prepares the code for potential publication, allowing other programs to consume it^[readme.md]. These paths typically reflect the location of the source code, such as github.com/google/go-cmp^[readme.md].

Creating a Module

A new Go module is initialized using the go mod init command followed by the desired module path^[readme.md].

go mod init github.com/example/project

This command creates the go.mod file necessary to track the code's dependencies^[readme.md].

Sources

^[readme.md]