Go Modules
Managing dependencies and project structure in Go
π¦ What are Go Modules?
Go Modules are the standard way to manage dependencies in Go projects. Introduced in Go 1.11, modules define project boundaries, track versions of dependencies, and make builds reproducible.
go mod init example.com/hello
// main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, Go Modules!")
}
Output:
Hello, Go Modules!
Key Module Concepts
Module
A module is a collection of Go packages with a versioned go.mod file.
go mod init github.com/user/project
go.mod File
Defines the module name and dependencies.
module github.com/user/project
go 1.22
go.sum File
Contains cryptographic checksums for dependency verification.
cat go.sum
Dependencies
Automatically managed using
go get
or
go mod tidy
.
go get github.com/fatih/color
πΉ Creating and Using a Go Module
Letβs create a Go module and use an external dependency.
π Step 1: Initialize a Module
mkdir greetapp
cd greetapp
go mod init example.com/greetapp
π Step 2: Add main.go
package main
import (
"fmt"
"rsc.io/quote"
)
func main() {
fmt.Println(quote.Go())
}
π Step 3: Download Dependencies
go mod tidy
Output:
Don't communicate by sharing memory, share memory by communicating.
πΉ Understanding go.mod File
The
go.mod
file is the heart of a Go module. It keeps track of the module path and dependencies.
module example.com/greetapp
go 1.22
require (
rsc.io/quote v1.5.2
)
- module: Defines your module path.
- go: Specifies the Go version.
- require: Lists module dependencies.
πΉ Common Go Module Commands
go mod init <module-path> # Initialize a module
go mod tidy # Clean and sync dependencies
go list -m all # List all modules
go get <module>@version # Add or update dependency
go mod graph # Show dependency graph
πΉ Example: Multi-Package Module
Example of a project organized with Go Modules:
// Project structure:
// greetapp/
// βββ go.mod
// βββ main.go
// βββ greet/
// βββ greet.go
// greet/greet.go
package greet
func Message(name string) string {
return "Hello, " + name + "!"
}
// main.go
package main
import (
"fmt"
"example.com/greetapp/greet"
)
func main() {
fmt.Println(greet.Message("Codorb"))
}
Output:
Hello, Codorb!