Go modules and dependencies
- Version
- 1.27
- Since
- 1.11
- Review
- Draft
Summary#
go.mod defines a module's import path prefix, Go version and dependency requirements. Use go mod init to start a module, go get to select a dependency version and go mod tidy to reconcile the requirements with the code.
Syntax#
go mod init example.com/myapp
go get example.com/dependency@v1.2.3
go mod tidy
Example#
This example imports a local module through replace. Both modules are created in one temporary directory and require no network access.
(
set -eu
dir=$(mktemp -d "${TMPDIR:-/tmp}/dlr-go-a-modules.XXXXXXXX")
trap 'rm -rf "$dir"' EXIT
trap 'exit 1' HUP INT TERM
cd "$dir"
export GO111MODULE=on GOWORK=off GOTOOLCHAIN=local GOPROXY=off
mkdir words
(cd words && go mod init example.com/words) >/dev/null 2>&1
cat > words/words.go <<'GO'
package words
func Greeting() string { return "ready to ship" }
GO
go mod init example.com/dispatch >/dev/null 2>&1
go mod edit -require=example.com/words@v0.0.0 \
-replace=example.com/words=./words
cat > main.go <<'GO'
package main
import (
"fmt"
"example.com/words"
)
func main() { fmt.Println(words.Greeting()) }
GO
go mod tidy
go list -m
go run .
)
Expected output#
example.com/dispatch
ready to ship
Common mistakes#
Run go mod init once at the module root. A local replace redirects a dependency but does not add a requirement for it. Before sharing the module, remove machine-specific replacements and commit go.mod and any generated go.sum. The latter records checksums for downloaded module content.
Version applicability#
Module commands and the example's require and replace forms arrived in Go 1.11. Module mode became the default in Go 1.16. Since Go 1.21, the go directive declares a minimum required toolchain version as well as the module's language version.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0