Go by Example: Modules
Go Modules are the official dependency management system for Go. This example shows how to import external packages and explains the workflow for initializing modules, adding dependencies, and maintaining the `go.mod` and `go.sum` files.
Code
package main
import (
"fmt"
// Importing an external package
// Run 'go get rsc.io/quote' to add this dependency
"rsc.io/quote"
)
func main() {
fmt.Println("Go Modules Demo")
// Use a function from the imported package
fmt.Println(quote.Go())
}
/*
SETUP INSTRUCTIONS:
1. Initialize a new module:
$ go mod init example/hello
2. Add the dependency (and download it):
$ go get rsc.io/quote
This updates go.mod and creates go.sum.
3. Run the program:
$ go run .
*/Explanation
Go Modules provide a structured way to manage dependencies in Go projects. A module is a collection of related Go packages that are versioned together as a single unit. The system is defined by the go.mod file, which sits at the root of your project and declares the module path (the project's unique identity) and its dependency requirements.
When you import a package that isn't in the standard library, Go looks at your go.mod file to resolve the version. The go get command is used to add, upgrade, or remove dependencies. Additionally, a go.sum file is automatically generated to maintain cryptographic checksums of the specific module versions you use, ensuring that your builds are reproducible and secure against tampering.
Key commands for module management:
go mod init [module-path]: Initialize a new module in the current directory.go get [package]: Add a dependency or upgrade it.go mod tidy: Remove unused dependencies and add missing ones.go mod verify: Check that dependencies match the expected checksums.

