Go by Example

Packages and Modules

A package groups Go files in one directory; a module records the project path, Go version and packages it uses.

A package groups Go files in one directory under the same package name. A module groups packages; its go.mod file records the import path, required Go version, and dependencies, which are other packages the project uses.

Start a module from the project directory. go mod init creates go.mod, and its go directive says which Go version the project requires.

From your project directory, run:

OUTPUT
$ go mod init example.com/hello
module example.com/hello
 
go 1.26

Put files for one package in a single directory. The greeting directory contains greeting.go. Uppercase names such as Hello are exported, meaning other packages can use them:

package greeting
 
func Hello(name string) string {
    return "Hello, " + name
}

A package's import path joins the module path and directory: example.com/hello plus greeting becomes example.com/hello/greeting. This main.go is at the module root:

package main
 
import (
    "fmt"
    "example.com/hello/greeting"
)
 
func main() {
    fmt.Println(greeting.Hello("Gopher"))
}

In production

Choose a module path your team controls. Run go mod tidy after imports change to add used packages and remove unused ones. Commit go.mod and go.sum so builds can verify dependencies.

Enjoyed this? Get more software craft delivered to your inbox.