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!

🧠 Test Your Knowledge

What command initializes a new Go module?