Go by Example

Packages and Modules

Packages group Go source files; modules record import paths, the minimum Go version, and external dependencies.

Every Go source file belongs to a package. A module groups packages and records their import path and dependencies in go.mod.

Start a module in the project directory. The go directive sets the minimum Go version required to build it.

Create go.mod with the module path used by packages that import this code:

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

Put related files in a package directory. A name that starts with an uppercase letter is exported and can be used by another package. This source is greeting/greeting.go:

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

Import the package by its module path followed by the package directory. This source is main.go:

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

In production

Use a module path your team controls. Run go mod tidy after changing imports, then commit go.mod and any generated go.sum so builds can verify declared dependencies.

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